blob: c87f10b150b4dc1374b6db3e60137f3f566a3851 [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
Chris Yea03dd232020-09-08 19:21:09 -070021#include <input/NamedEnum.h>
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070022#include "TouchInputMapper.h"
23
24#include "CursorButtonAccumulator.h"
25#include "CursorScrollAccumulator.h"
26#include "TouchButtonAccumulator.h"
27#include "TouchCursorInputMapperCommon.h"
28
29namespace android {
30
31// --- Constants ---
32
33// Maximum amount of latency to add to touch events while waiting for data from an
34// external stylus.
35static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
36
37// Maximum amount of time to wait on touch data before pushing out new pressure data.
38static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
39
40// Artificial latency on synthetic events created from stylus data without corresponding touch
41// data.
42static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
43
44// --- Static Definitions ---
45
46template <typename T>
47inline static void swap(T& a, T& b) {
48 T temp = a;
49 a = b;
50 b = temp;
51}
52
53static float calculateCommonVector(float a, float b) {
54 if (a > 0 && b > 0) {
55 return a < b ? a : b;
56 } else if (a < 0 && b < 0) {
57 return a > b ? a : b;
58 } else {
59 return 0;
60 }
61}
62
63inline static float distance(float x1, float y1, float x2, float y2) {
64 return hypotf(x1 - x2, y1 - y2);
65}
66
67inline static int32_t signExtendNybble(int32_t value) {
68 return value >= 8 ? value - 16 : value;
69}
70
71// --- RawPointerAxes ---
72
73RawPointerAxes::RawPointerAxes() {
74 clear();
75}
76
77void RawPointerAxes::clear() {
78 x.clear();
79 y.clear();
80 pressure.clear();
81 touchMajor.clear();
82 touchMinor.clear();
83 toolMajor.clear();
84 toolMinor.clear();
85 orientation.clear();
86 distance.clear();
87 tiltX.clear();
88 tiltY.clear();
89 trackingId.clear();
90 slot.clear();
91}
92
93// --- RawPointerData ---
94
95RawPointerData::RawPointerData() {
96 clear();
97}
98
99void RawPointerData::clear() {
100 pointerCount = 0;
101 clearIdBits();
102}
103
104void RawPointerData::copyFrom(const RawPointerData& other) {
105 pointerCount = other.pointerCount;
106 hoveringIdBits = other.hoveringIdBits;
107 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800108 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109
110 for (uint32_t i = 0; i < pointerCount; i++) {
111 pointers[i] = other.pointers[i];
112
113 int id = pointers[i].id;
114 idToIndex[id] = other.idToIndex[id];
115 }
116}
117
118void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
119 float x = 0, y = 0;
120 uint32_t count = touchingIdBits.count();
121 if (count) {
122 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
123 uint32_t id = idBits.clearFirstMarkedBit();
124 const Pointer& pointer = pointerForId(id);
125 x += pointer.x;
126 y += pointer.y;
127 }
128 x /= count;
129 y /= count;
130 }
131 *outX = x;
132 *outY = y;
133}
134
135// --- CookedPointerData ---
136
137CookedPointerData::CookedPointerData() {
138 clear();
139}
140
141void CookedPointerData::clear() {
142 pointerCount = 0;
143 hoveringIdBits.clear();
144 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800145 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000146 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700147}
148
149void CookedPointerData::copyFrom(const CookedPointerData& other) {
150 pointerCount = other.pointerCount;
151 hoveringIdBits = other.hoveringIdBits;
152 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000153 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700154
155 for (uint32_t i = 0; i < pointerCount; i++) {
156 pointerProperties[i].copyFrom(other.pointerProperties[i]);
157 pointerCoords[i].copyFrom(other.pointerCoords[i]);
158
159 int id = pointerProperties[i].id;
160 idToIndex[id] = other.idToIndex[id];
161 }
162}
163
164// --- TouchInputMapper ---
165
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800166TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
167 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700168 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100169 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800170 mRawSurfaceWidth(-1),
171 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700172 mSurfaceLeft(0),
173 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700174 mSurfaceRight(0),
175 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700176 mPhysicalWidth(-1),
177 mPhysicalHeight(-1),
178 mPhysicalLeft(0),
179 mPhysicalTop(0),
180 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
181
182TouchInputMapper::~TouchInputMapper() {}
183
184uint32_t TouchInputMapper::getSources() {
185 return mSource;
186}
187
188void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
189 InputMapper::populateDeviceInfo(info);
190
Michael Wright227c5542020-07-02 18:30:52 +0100191 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 info->addMotionRange(mOrientedRanges.x);
193 info->addMotionRange(mOrientedRanges.y);
194 info->addMotionRange(mOrientedRanges.pressure);
195
Chris Yef74dc422020-09-02 22:41:50 -0700196 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700197 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
198 //
199 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
200 // motion, i.e. the hardware dimensions, as the finger could move completely across the
201 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700202 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
203 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
204 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
205 x.fuzz, x.resolution);
206 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
207 y.fuzz, y.resolution);
208 }
209
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700210 if (mOrientedRanges.haveSize) {
211 info->addMotionRange(mOrientedRanges.size);
212 }
213
214 if (mOrientedRanges.haveTouchSize) {
215 info->addMotionRange(mOrientedRanges.touchMajor);
216 info->addMotionRange(mOrientedRanges.touchMinor);
217 }
218
219 if (mOrientedRanges.haveToolSize) {
220 info->addMotionRange(mOrientedRanges.toolMajor);
221 info->addMotionRange(mOrientedRanges.toolMinor);
222 }
223
224 if (mOrientedRanges.haveOrientation) {
225 info->addMotionRange(mOrientedRanges.orientation);
226 }
227
228 if (mOrientedRanges.haveDistance) {
229 info->addMotionRange(mOrientedRanges.distance);
230 }
231
232 if (mOrientedRanges.haveTilt) {
233 info->addMotionRange(mOrientedRanges.tilt);
234 }
235
236 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
237 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
238 0.0f);
239 }
240 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
241 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
242 0.0f);
243 }
Michael Wright227c5542020-07-02 18:30:52 +0100244 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700245 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
246 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
247 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
248 x.fuzz, x.resolution);
249 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
250 y.fuzz, y.resolution);
251 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
252 x.fuzz, x.resolution);
253 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
254 y.fuzz, y.resolution);
255 }
256 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
257 }
258}
259
260void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700261 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
262 NamedEnum::string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700263 dumpParameters(dump);
264 dumpVirtualKeys(dump);
265 dumpRawPointerAxes(dump);
266 dumpCalibration(dump);
267 dumpAffineTransformation(dump);
268 dumpSurface(dump);
269
270 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
271 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
272 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
273 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
274 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
275 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
276 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
277 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
278 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
279 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
280 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
281 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
282 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
283 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
284 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
285 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
286 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
287
288 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
289 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
290 mLastRawState.rawPointerData.pointerCount);
291 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
292 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
293 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
294 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
295 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
296 "toolType=%d, isHovering=%s\n",
297 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
298 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
299 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
300 pointer.distance, pointer.toolType, toString(pointer.isHovering));
301 }
302
303 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
304 mLastCookedState.buttonState);
305 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
306 mLastCookedState.cookedPointerData.pointerCount);
307 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
308 const PointerProperties& pointerProperties =
309 mLastCookedState.cookedPointerData.pointerProperties[i];
310 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000311 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
312 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
313 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
315 "toolType=%d, isHovering=%s\n",
316 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
327 pointerProperties.toolType,
328 toString(mLastCookedState.cookedPointerData.isHovering(i)));
329 }
330
331 dump += INDENT3 "Stylus Fusion:\n";
332 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
333 toString(mExternalStylusConnected));
334 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
335 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
336 mExternalStylusFusionTimeout);
337 dump += INDENT3 "External Stylus State:\n";
338 dumpStylusState(dump, mExternalStylusState);
339
Michael Wright227c5542020-07-02 18:30:52 +0100340 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
342 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
343 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
344 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
345 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
346 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
347 }
348}
349
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350void 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.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -0600400 getContext()->notifyDeviceReset(when, getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700401 }
402}
403
404void TouchInputMapper::resolveExternalStylusPresence() {
405 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800406 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700407 mExternalStylusConnected = !devices.empty();
408
409 if (!mExternalStylusConnected) {
410 resetExternalStylus();
411 }
412}
413
414void TouchInputMapper::configureParameters() {
415 // Use the pointer presentation mode for devices that do not support distinct
416 // multitouch. The spot-based presentation relies on being able to accurately
417 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100419 ? Parameters::GestureMode::SINGLE_TOUCH
420 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421
422 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800423 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
424 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700425 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100426 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700427 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100428 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700429 } else if (gestureModeString != "default") {
430 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
431 }
432 }
433
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800434 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700435 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100436 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800437 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100439 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800440 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
441 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700442 // The device is a cursor device with a touch pad attached.
443 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100444 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700445 } else {
446 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100447 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448 }
449
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800450 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700451
452 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800453 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
454 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100456 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100458 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100460 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700461 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100462 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463 } else if (deviceTypeString != "default") {
464 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
465 }
466 }
467
Michael Wright227c5542020-07-02 18:30:52 +0100468 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800469 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
470 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700471
472 mParameters.hasAssociatedDisplay = false;
473 mParameters.associatedDisplayIsExternal = false;
474 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100475 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
476 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700477 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100478 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800479 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700480 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800481 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
482 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700483 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
484 }
485 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800486 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700487 mParameters.hasAssociatedDisplay = true;
488 }
489
490 // Initial downs on external touch devices should wake the device.
491 // Normally we don't do this for internal touch screens to prevent them from waking
492 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800493 mParameters.wake = getDeviceContext().isExternal();
494 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700495}
496
497void TouchInputMapper::dumpParameters(std::string& dump) {
498 dump += INDENT3 "Parameters:\n";
499
Chris Yea03dd232020-09-08 19:21:09 -0700500 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700501
Chris Yea03dd232020-09-08 19:21:09 -0700502 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700503
504 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
505 "displayId='%s'\n",
506 toString(mParameters.hasAssociatedDisplay),
507 toString(mParameters.associatedDisplayIsExternal),
508 mParameters.uniqueDisplayId.c_str());
509 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
510}
511
512void TouchInputMapper::configureRawPointerAxes() {
513 mRawPointerAxes.clear();
514}
515
516void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
517 dump += INDENT3 "Raw Touch Axes:\n";
518 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
531}
532
533bool TouchInputMapper::hasExternalStylus() const {
534 return mExternalStylusConnected;
535}
536
537/**
538 * Determine which DisplayViewport to use.
539 * 1. If display port is specified, return the matching viewport. If matching viewport not
540 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800541 * 2. Always use the suggested viewport from WindowManagerService for pointers.
542 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700543 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800544 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700545 */
546std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800547 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800548 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700549 if (displayPort) {
550 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800551 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700552 }
553
Michael Wright227c5542020-07-02 18:30:52 +0100554 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800555 std::optional<DisplayViewport> viewport =
556 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
557 if (viewport) {
558 return viewport;
559 } else {
560 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
561 mConfig.defaultPointerDisplayId);
562 }
563 }
564
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700565 // Check if uniqueDisplayId is specified in idc file.
566 if (!mParameters.uniqueDisplayId.empty()) {
567 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
568 }
569
570 ViewportType viewportTypeToUse;
571 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100572 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700573 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100574 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700575 }
576
577 std::optional<DisplayViewport> viewport =
578 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100579 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700580 ALOGW("Input device %s should be associated with external display, "
581 "fallback to internal one for the external viewport is not found.",
582 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100583 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700584 }
585
586 return viewport;
587 }
588
589 // No associated display, return a non-display viewport.
590 DisplayViewport newViewport;
591 // Raw width and height in the natural orientation.
592 int32_t rawWidth = mRawPointerAxes.getRawWidth();
593 int32_t rawHeight = mRawPointerAxes.getRawHeight();
594 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
595 return std::make_optional(newViewport);
596}
597
598void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100599 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700600
601 resolveExternalStylusPresence();
602
603 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100604 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800605 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700606 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100607 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700608 if (hasStylus()) {
609 mSource |= AINPUT_SOURCE_STYLUS;
610 }
Michael Wright227c5542020-07-02 18:30:52 +0100611 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700612 mParameters.hasAssociatedDisplay) {
613 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100614 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700615 if (hasStylus()) {
616 mSource |= AINPUT_SOURCE_STYLUS;
617 }
618 if (hasExternalStylus()) {
619 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
620 }
Michael Wright227c5542020-07-02 18:30:52 +0100621 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700622 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100623 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700624 } else {
625 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100626 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700627 }
628
629 // Ensure we have valid X and Y axes.
630 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
631 ALOGW("Touch device '%s' did not report support for X or Y axis! "
632 "The device will be inoperable.",
633 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100634 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700635 return;
636 }
637
638 // Get associated display dimensions.
639 std::optional<DisplayViewport> newViewport = findViewport();
640 if (!newViewport) {
641 ALOGI("Touch device '%s' could not query the properties of its associated "
642 "display. The device will be inoperable until the display size "
643 "becomes available.",
644 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100645 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700646 return;
647 }
648
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000649 if (!newViewport->isActive) {
650 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
651 getDeviceName().c_str(), getDeviceId());
652 mDeviceMode = DeviceMode::DISABLED;
653 return;
654 }
655
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700656 // Raw width and height in the natural orientation.
657 int32_t rawWidth = mRawPointerAxes.getRawWidth();
658 int32_t rawHeight = mRawPointerAxes.getRawHeight();
659
660 bool viewportChanged = mViewport != *newViewport;
661 if (viewportChanged) {
662 mViewport = *newViewport;
663
Michael Wright227c5542020-07-02 18:30:52 +0100664 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700665 // Convert rotated viewport to natural surface coordinates.
666 int32_t naturalLogicalWidth, naturalLogicalHeight;
667 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
668 int32_t naturalPhysicalLeft, naturalPhysicalTop;
669 int32_t naturalDeviceWidth, naturalDeviceHeight;
670 switch (mViewport.orientation) {
671 case DISPLAY_ORIENTATION_90:
672 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
673 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
674 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
675 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800676 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700677 naturalPhysicalTop = mViewport.physicalLeft;
678 naturalDeviceWidth = mViewport.deviceHeight;
679 naturalDeviceHeight = mViewport.deviceWidth;
680 break;
681 case DISPLAY_ORIENTATION_180:
682 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
683 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
684 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
685 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
686 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
687 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
688 naturalDeviceWidth = mViewport.deviceWidth;
689 naturalDeviceHeight = mViewport.deviceHeight;
690 break;
691 case DISPLAY_ORIENTATION_270:
692 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
693 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
694 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
695 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
696 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800697 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700698 naturalDeviceWidth = mViewport.deviceHeight;
699 naturalDeviceHeight = mViewport.deviceWidth;
700 break;
701 case DISPLAY_ORIENTATION_0:
702 default:
703 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
704 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
705 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
706 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
707 naturalPhysicalLeft = mViewport.physicalLeft;
708 naturalPhysicalTop = mViewport.physicalTop;
709 naturalDeviceWidth = mViewport.deviceWidth;
710 naturalDeviceHeight = mViewport.deviceHeight;
711 break;
712 }
713
714 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
715 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
716 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
717 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
718 }
719
720 mPhysicalWidth = naturalPhysicalWidth;
721 mPhysicalHeight = naturalPhysicalHeight;
722 mPhysicalLeft = naturalPhysicalLeft;
723 mPhysicalTop = naturalPhysicalTop;
724
Arthur Hung4197f6b2020-03-16 15:39:59 +0800725 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
726 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700727 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
728 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800729 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
730 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700731
732 mSurfaceOrientation =
733 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
734 } else {
735 mPhysicalWidth = rawWidth;
736 mPhysicalHeight = rawHeight;
737 mPhysicalLeft = 0;
738 mPhysicalTop = 0;
739
Arthur Hung4197f6b2020-03-16 15:39:59 +0800740 mRawSurfaceWidth = rawWidth;
741 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700742 mSurfaceLeft = 0;
743 mSurfaceTop = 0;
744 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
745 }
746 }
747
748 // If moving between pointer modes, need to reset some state.
749 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
750 if (deviceModeChanged) {
751 mOrientedRanges.clear();
752 }
753
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800754 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
755 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100756 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800757 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
758 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800759 if (mPointerController == nullptr) {
760 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700761 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800762 if (mConfig.pointerCapture) {
763 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
764 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700765 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100766 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700767 }
768
769 if (viewportChanged || deviceModeChanged) {
770 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
771 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800772 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700773 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
774
775 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800776 mXScale = float(mRawSurfaceWidth) / rawWidth;
777 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700778 mXTranslate = -mSurfaceLeft;
779 mYTranslate = -mSurfaceTop;
780 mXPrecision = 1.0f / mXScale;
781 mYPrecision = 1.0f / mYScale;
782
783 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
784 mOrientedRanges.x.source = mSource;
785 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
786 mOrientedRanges.y.source = mSource;
787
788 configureVirtualKeys();
789
790 // Scale factor for terms that are not oriented in a particular axis.
791 // If the pixels are square then xScale == yScale otherwise we fake it
792 // by choosing an average.
793 mGeometricScale = avg(mXScale, mYScale);
794
795 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800796 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700797
798 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100799 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700800 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
801 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
802 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
803 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
804 } else {
805 mSizeScale = 0.0f;
806 }
807
808 mOrientedRanges.haveTouchSize = true;
809 mOrientedRanges.haveToolSize = true;
810 mOrientedRanges.haveSize = true;
811
812 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
813 mOrientedRanges.touchMajor.source = mSource;
814 mOrientedRanges.touchMajor.min = 0;
815 mOrientedRanges.touchMajor.max = diagonalSize;
816 mOrientedRanges.touchMajor.flat = 0;
817 mOrientedRanges.touchMajor.fuzz = 0;
818 mOrientedRanges.touchMajor.resolution = 0;
819
820 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
821 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
822
823 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
824 mOrientedRanges.toolMajor.source = mSource;
825 mOrientedRanges.toolMajor.min = 0;
826 mOrientedRanges.toolMajor.max = diagonalSize;
827 mOrientedRanges.toolMajor.flat = 0;
828 mOrientedRanges.toolMajor.fuzz = 0;
829 mOrientedRanges.toolMajor.resolution = 0;
830
831 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
832 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
833
834 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
835 mOrientedRanges.size.source = mSource;
836 mOrientedRanges.size.min = 0;
837 mOrientedRanges.size.max = 1.0;
838 mOrientedRanges.size.flat = 0;
839 mOrientedRanges.size.fuzz = 0;
840 mOrientedRanges.size.resolution = 0;
841 } else {
842 mSizeScale = 0.0f;
843 }
844
845 // Pressure factors.
846 mPressureScale = 0;
847 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100848 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
849 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700850 if (mCalibration.havePressureScale) {
851 mPressureScale = mCalibration.pressureScale;
852 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
853 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
854 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
855 }
856 }
857
858 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
859 mOrientedRanges.pressure.source = mSource;
860 mOrientedRanges.pressure.min = 0;
861 mOrientedRanges.pressure.max = pressureMax;
862 mOrientedRanges.pressure.flat = 0;
863 mOrientedRanges.pressure.fuzz = 0;
864 mOrientedRanges.pressure.resolution = 0;
865
866 // Tilt
867 mTiltXCenter = 0;
868 mTiltXScale = 0;
869 mTiltYCenter = 0;
870 mTiltYScale = 0;
871 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
872 if (mHaveTilt) {
873 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
874 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
875 mTiltXScale = M_PI / 180;
876 mTiltYScale = M_PI / 180;
877
878 mOrientedRanges.haveTilt = true;
879
880 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
881 mOrientedRanges.tilt.source = mSource;
882 mOrientedRanges.tilt.min = 0;
883 mOrientedRanges.tilt.max = M_PI_2;
884 mOrientedRanges.tilt.flat = 0;
885 mOrientedRanges.tilt.fuzz = 0;
886 mOrientedRanges.tilt.resolution = 0;
887 }
888
889 // Orientation
890 mOrientationScale = 0;
891 if (mHaveTilt) {
892 mOrientedRanges.haveOrientation = true;
893
894 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
895 mOrientedRanges.orientation.source = mSource;
896 mOrientedRanges.orientation.min = -M_PI;
897 mOrientedRanges.orientation.max = M_PI;
898 mOrientedRanges.orientation.flat = 0;
899 mOrientedRanges.orientation.fuzz = 0;
900 mOrientedRanges.orientation.resolution = 0;
901 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100902 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100904 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700905 if (mRawPointerAxes.orientation.valid) {
906 if (mRawPointerAxes.orientation.maxValue > 0) {
907 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
908 } else if (mRawPointerAxes.orientation.minValue < 0) {
909 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
910 } else {
911 mOrientationScale = 0;
912 }
913 }
914 }
915
916 mOrientedRanges.haveOrientation = true;
917
918 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
919 mOrientedRanges.orientation.source = mSource;
920 mOrientedRanges.orientation.min = -M_PI_2;
921 mOrientedRanges.orientation.max = M_PI_2;
922 mOrientedRanges.orientation.flat = 0;
923 mOrientedRanges.orientation.fuzz = 0;
924 mOrientedRanges.orientation.resolution = 0;
925 }
926
927 // Distance
928 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100929 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
930 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 if (mCalibration.haveDistanceScale) {
932 mDistanceScale = mCalibration.distanceScale;
933 } else {
934 mDistanceScale = 1.0f;
935 }
936 }
937
938 mOrientedRanges.haveDistance = true;
939
940 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
941 mOrientedRanges.distance.source = mSource;
942 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
943 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
944 mOrientedRanges.distance.flat = 0;
945 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
946 mOrientedRanges.distance.resolution = 0;
947 }
948
949 // Compute oriented precision, scales and ranges.
950 // Note that the maximum value reported is an inclusive maximum value so it is one
951 // unit less than the total width or height of surface.
952 switch (mSurfaceOrientation) {
953 case DISPLAY_ORIENTATION_90:
954 case DISPLAY_ORIENTATION_270:
955 mOrientedXPrecision = mYPrecision;
956 mOrientedYPrecision = mXPrecision;
957
958 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800959 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700960 mOrientedRanges.x.flat = 0;
961 mOrientedRanges.x.fuzz = 0;
962 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
963
964 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800965 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966 mOrientedRanges.y.flat = 0;
967 mOrientedRanges.y.fuzz = 0;
968 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
969 break;
970
971 default:
972 mOrientedXPrecision = mXPrecision;
973 mOrientedYPrecision = mYPrecision;
974
975 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800976 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977 mOrientedRanges.x.flat = 0;
978 mOrientedRanges.x.fuzz = 0;
979 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
980
981 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800982 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700983 mOrientedRanges.y.flat = 0;
984 mOrientedRanges.y.fuzz = 0;
985 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
986 break;
987 }
988
989 // Location
990 updateAffineTransformation();
991
Michael Wright227c5542020-07-02 18:30:52 +0100992 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700993 // Compute pointer gesture detection parameters.
994 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +0800995 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996
997 // Scale movements such that one whole swipe of the touch pad covers a
998 // given area relative to the diagonal size of the display when no acceleration
999 // is applied.
1000 // Assume that the touch pad has a square aspect ratio such that movements in
1001 // X and Y of the same number of raw units cover the same physical distance.
1002 mPointerXMovementScale =
1003 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1004 mPointerYMovementScale = mPointerXMovementScale;
1005
1006 // Scale zooms to cover a smaller range of the display than movements do.
1007 // This value determines the area around the pointer that is affected by freeform
1008 // pointer gestures.
1009 mPointerXZoomScale =
1010 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1011 mPointerYZoomScale = mPointerXZoomScale;
1012
1013 // Max width between pointers to detect a swipe gesture is more than some fraction
1014 // of the diagonal axis of the touch pad. Touches that are wider than this are
1015 // translated into freeform gestures.
1016 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1017
1018 // Abort current pointer usages because the state has changed.
1019 abortPointerUsage(when, 0 /*policyFlags*/);
1020 }
1021
1022 // Inform the dispatcher about the changes.
1023 *outResetNeeded = true;
1024 bumpGeneration();
1025 }
1026}
1027
1028void TouchInputMapper::dumpSurface(std::string& dump) {
1029 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001030 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1031 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1033 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001034 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1035 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001036 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1037 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1038 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1039 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1040 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1041}
1042
1043void TouchInputMapper::configureVirtualKeys() {
1044 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001045 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001046
1047 mVirtualKeys.clear();
1048
1049 if (virtualKeyDefinitions.size() == 0) {
1050 return;
1051 }
1052
1053 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1054 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1055 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1056 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1057
1058 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1059 VirtualKey virtualKey;
1060
1061 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1062 int32_t keyCode;
1063 int32_t dummyKeyMetaState;
1064 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001065 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1066 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1068 continue; // drop the key
1069 }
1070
1071 virtualKey.keyCode = keyCode;
1072 virtualKey.flags = flags;
1073
1074 // convert the key definition's display coordinates into touch coordinates for a hit box
1075 int32_t halfWidth = virtualKeyDefinition.width / 2;
1076 int32_t halfHeight = virtualKeyDefinition.height / 2;
1077
1078 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001079 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001080 touchScreenLeft;
1081 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001082 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001083 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001084 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1085 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001087 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1088 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001089 touchScreenTop;
1090 mVirtualKeys.push_back(virtualKey);
1091 }
1092}
1093
1094void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1095 if (!mVirtualKeys.empty()) {
1096 dump += INDENT3 "Virtual Keys:\n";
1097
1098 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1099 const VirtualKey& virtualKey = mVirtualKeys[i];
1100 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1101 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1102 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1103 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1104 }
1105 }
1106}
1107
1108void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001109 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110 Calibration& out = mCalibration;
1111
1112 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001113 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001114 String8 sizeCalibrationString;
1115 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1116 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001117 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001118 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001119 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001120 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001121 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001122 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001123 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001124 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001125 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 } else if (sizeCalibrationString != "default") {
1127 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1128 }
1129 }
1130
1131 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1132 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1133 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1134
1135 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 String8 pressureCalibrationString;
1138 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1139 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (pressureCalibrationString != "default") {
1146 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1147 pressureCalibrationString.string());
1148 }
1149 }
1150
1151 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1152
1153 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001154 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 String8 orientationCalibrationString;
1156 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1157 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001158 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001160 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001161 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001163 } else if (orientationCalibrationString != "default") {
1164 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1165 orientationCalibrationString.string());
1166 }
1167 }
1168
1169 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 String8 distanceCalibrationString;
1172 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1173 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001174 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001176 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 } else if (distanceCalibrationString != "default") {
1178 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1179 distanceCalibrationString.string());
1180 }
1181 }
1182
1183 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1184
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 String8 coverageCalibrationString;
1187 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1188 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 } else if (coverageCalibrationString != "default") {
1193 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1194 coverageCalibrationString.string());
1195 }
1196 }
1197}
1198
1199void TouchInputMapper::resolveCalibration() {
1200 // Size
1201 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001202 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1203 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 }
1205 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001206 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 }
1208
1209 // Pressure
1210 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001211 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1212 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 }
1214 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001215 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 }
1217
1218 // Orientation
1219 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001220 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1221 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 }
1223 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001224 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 }
1226
1227 // Distance
1228 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001229 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1230 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 }
1232 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001233 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 }
1235
1236 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001237 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1238 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 }
1240}
1241
1242void TouchInputMapper::dumpCalibration(std::string& dump) {
1243 dump += INDENT3 "Calibration:\n";
1244
1245 // Size
1246 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001247 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 dump += INDENT4 "touch.size.calibration: none\n";
1249 break;
Michael Wright227c5542020-07-02 18:30:52 +01001250 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 dump += INDENT4 "touch.size.calibration: geometric\n";
1252 break;
Michael Wright227c5542020-07-02 18:30:52 +01001253 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 dump += INDENT4 "touch.size.calibration: diameter\n";
1255 break;
Michael Wright227c5542020-07-02 18:30:52 +01001256 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 dump += INDENT4 "touch.size.calibration: box\n";
1258 break;
Michael Wright227c5542020-07-02 18:30:52 +01001259 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 dump += INDENT4 "touch.size.calibration: area\n";
1261 break;
1262 default:
1263 ALOG_ASSERT(false);
1264 }
1265
1266 if (mCalibration.haveSizeScale) {
1267 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1268 }
1269
1270 if (mCalibration.haveSizeBias) {
1271 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1272 }
1273
1274 if (mCalibration.haveSizeIsSummed) {
1275 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1276 toString(mCalibration.sizeIsSummed));
1277 }
1278
1279 // Pressure
1280 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001281 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 dump += INDENT4 "touch.pressure.calibration: none\n";
1283 break;
Michael Wright227c5542020-07-02 18:30:52 +01001284 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 dump += INDENT4 "touch.pressure.calibration: physical\n";
1286 break;
Michael Wright227c5542020-07-02 18:30:52 +01001287 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1289 break;
1290 default:
1291 ALOG_ASSERT(false);
1292 }
1293
1294 if (mCalibration.havePressureScale) {
1295 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1296 }
1297
1298 // Orientation
1299 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001300 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += INDENT4 "touch.orientation.calibration: none\n";
1302 break;
Michael Wright227c5542020-07-02 18:30:52 +01001303 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1305 break;
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.orientation.calibration: vector\n";
1308 break;
1309 default:
1310 ALOG_ASSERT(false);
1311 }
1312
1313 // Distance
1314 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.distance.calibration: none\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.distance.calibration: scaled\n";
1320 break;
1321 default:
1322 ALOG_ASSERT(false);
1323 }
1324
1325 if (mCalibration.haveDistanceScale) {
1326 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1327 }
1328
1329 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.coverage.calibration: none\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.coverage.calibration: box\n";
1335 break;
1336 default:
1337 ALOG_ASSERT(false);
1338 }
1339}
1340
1341void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1342 dump += INDENT3 "Affine Transformation:\n";
1343
1344 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1345 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1346 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1347 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1348 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1349 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1350}
1351
1352void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001353 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001354 mSurfaceOrientation);
1355}
1356
1357void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001358 mCursorButtonAccumulator.reset(getDeviceContext());
1359 mCursorScrollAccumulator.reset(getDeviceContext());
1360 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361
1362 mPointerVelocityControl.reset();
1363 mWheelXVelocityControl.reset();
1364 mWheelYVelocityControl.reset();
1365
1366 mRawStatesPending.clear();
1367 mCurrentRawState.clear();
1368 mCurrentCookedState.clear();
1369 mLastRawState.clear();
1370 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001371 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001372 mSentHoverEnter = false;
1373 mHavePointerIds = false;
1374 mCurrentMotionAborted = false;
1375 mDownTime = 0;
1376
1377 mCurrentVirtualKey.down = false;
1378
1379 mPointerGesture.reset();
1380 mPointerSimple.reset();
1381 resetExternalStylus();
1382
1383 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001384 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001385 mPointerController->clearSpots();
1386 }
1387
1388 InputMapper::reset(when);
1389}
1390
1391void TouchInputMapper::resetExternalStylus() {
1392 mExternalStylusState.clear();
1393 mExternalStylusId = -1;
1394 mExternalStylusFusionTimeout = LLONG_MAX;
1395 mExternalStylusDataPending = false;
1396}
1397
1398void TouchInputMapper::clearStylusDataPendingFlags() {
1399 mExternalStylusDataPending = false;
1400 mExternalStylusFusionTimeout = LLONG_MAX;
1401}
1402
1403void TouchInputMapper::process(const RawEvent* rawEvent) {
1404 mCursorButtonAccumulator.process(rawEvent);
1405 mCursorScrollAccumulator.process(rawEvent);
1406 mTouchButtonAccumulator.process(rawEvent);
1407
1408 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1409 sync(rawEvent->when);
1410 }
1411}
1412
1413void TouchInputMapper::sync(nsecs_t when) {
1414 const RawState* last =
1415 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1416
1417 // Push a new state.
1418 mRawStatesPending.emplace_back();
1419
1420 RawState* next = &mRawStatesPending.back();
1421 next->clear();
1422 next->when = when;
1423
1424 // Sync button state.
1425 next->buttonState =
1426 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1427
1428 // Sync scroll
1429 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1430 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1431 mCursorScrollAccumulator.finishSync();
1432
1433 // Sync touch
1434 syncTouch(when, next);
1435
1436 // Assign pointer ids.
1437 if (!mHavePointerIds) {
1438 assignPointerIds(last, next);
1439 }
1440
1441#if DEBUG_RAW_EVENTS
1442 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001443 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1445 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001446 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1447 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001448#endif
1449
1450 processRawTouches(false /*timeout*/);
1451}
1452
1453void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001454 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455 // Drop all input if the device is disabled.
1456 mCurrentRawState.clear();
1457 mRawStatesPending.clear();
1458 return;
1459 }
1460
1461 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1462 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1463 // touching the current state will only observe the events that have been dispatched to the
1464 // rest of the pipeline.
1465 const size_t N = mRawStatesPending.size();
1466 size_t count;
1467 for (count = 0; count < N; count++) {
1468 const RawState& next = mRawStatesPending[count];
1469
1470 // A failure to assign the stylus id means that we're waiting on stylus data
1471 // and so should defer the rest of the pipeline.
1472 if (assignExternalStylusId(next, timeout)) {
1473 break;
1474 }
1475
1476 // All ready to go.
1477 clearStylusDataPendingFlags();
1478 mCurrentRawState.copyFrom(next);
1479 if (mCurrentRawState.when < mLastRawState.when) {
1480 mCurrentRawState.when = mLastRawState.when;
1481 }
1482 cookAndDispatch(mCurrentRawState.when);
1483 }
1484 if (count != 0) {
1485 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1486 }
1487
1488 if (mExternalStylusDataPending) {
1489 if (timeout) {
1490 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1491 clearStylusDataPendingFlags();
1492 mCurrentRawState.copyFrom(mLastRawState);
1493#if DEBUG_STYLUS_FUSION
1494 ALOGD("Timeout expired, synthesizing event with new stylus data");
1495#endif
1496 cookAndDispatch(when);
1497 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1498 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1499 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1500 }
1501 }
1502}
1503
1504void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1505 // Always start with a clean state.
1506 mCurrentCookedState.clear();
1507
1508 // Apply stylus buttons to current raw state.
1509 applyExternalStylusButtonState(when);
1510
1511 // Handle policy on initial down or hover events.
1512 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1513 mCurrentRawState.rawPointerData.pointerCount != 0;
1514
1515 uint32_t policyFlags = 0;
1516 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1517 if (initialDown || buttonsPressed) {
1518 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001519 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001520 getContext()->fadePointer();
1521 }
1522
1523 if (mParameters.wake) {
1524 policyFlags |= POLICY_FLAG_WAKE;
1525 }
1526 }
1527
1528 // Consume raw off-screen touches before cooking pointer data.
1529 // If touches are consumed, subsequent code will not receive any pointer data.
1530 if (consumeRawTouches(when, policyFlags)) {
1531 mCurrentRawState.rawPointerData.clear();
1532 }
1533
1534 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1535 // with cooked pointer data that has the same ids and indices as the raw data.
1536 // The following code can use either the raw or cooked data, as needed.
1537 cookPointerData();
1538
1539 // Apply stylus pressure to current cooked state.
1540 applyExternalStylusTouchState(when);
1541
1542 // Synthesize key down from raw buttons if needed.
1543 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1544 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1545 mCurrentCookedState.buttonState);
1546
1547 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001548 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001549 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1550 uint32_t id = idBits.clearFirstMarkedBit();
1551 const RawPointerData::Pointer& pointer =
1552 mCurrentRawState.rawPointerData.pointerForId(id);
1553 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1554 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1555 mCurrentCookedState.stylusIdBits.markBit(id);
1556 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1557 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1558 mCurrentCookedState.fingerIdBits.markBit(id);
1559 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1560 mCurrentCookedState.mouseIdBits.markBit(id);
1561 }
1562 }
1563 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1564 uint32_t id = idBits.clearFirstMarkedBit();
1565 const RawPointerData::Pointer& pointer =
1566 mCurrentRawState.rawPointerData.pointerForId(id);
1567 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1568 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1569 mCurrentCookedState.stylusIdBits.markBit(id);
1570 }
1571 }
1572
1573 // Stylus takes precedence over all tools, then mouse, then finger.
1574 PointerUsage pointerUsage = mPointerUsage;
1575 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1576 mCurrentCookedState.mouseIdBits.clear();
1577 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001578 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1580 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001581 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001582 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1583 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001584 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001585 }
1586
1587 dispatchPointerUsage(when, policyFlags, pointerUsage);
1588 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001589 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590 mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001591 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1592 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001593
1594 mPointerController->setButtonState(mCurrentRawState.buttonState);
1595 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1596 mCurrentCookedState.cookedPointerData.idToIndex,
1597 mCurrentCookedState.cookedPointerData.touchingIdBits,
1598 mViewport.displayId);
1599 }
1600
1601 if (!mCurrentMotionAborted) {
1602 dispatchButtonRelease(when, policyFlags);
1603 dispatchHoverExit(when, policyFlags);
1604 dispatchTouches(when, policyFlags);
1605 dispatchHoverEnterAndMove(when, policyFlags);
1606 dispatchButtonPress(when, policyFlags);
1607 }
1608
1609 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1610 mCurrentMotionAborted = false;
1611 }
1612 }
1613
1614 // Synthesize key up from raw buttons if needed.
1615 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1616 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1617 mCurrentCookedState.buttonState);
1618
1619 // Clear some transient state.
1620 mCurrentRawState.rawVScroll = 0;
1621 mCurrentRawState.rawHScroll = 0;
1622
1623 // Copy current touch to last touch in preparation for the next cycle.
1624 mLastRawState.copyFrom(mCurrentRawState);
1625 mLastCookedState.copyFrom(mCurrentCookedState);
1626}
1627
1628void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001629 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1631 }
1632}
1633
1634void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1635 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1636 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1637
1638 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1639 float pressure = mExternalStylusState.pressure;
1640 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1641 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1642 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1643 }
1644 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1645 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1646
1647 PointerProperties& properties =
1648 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1649 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1650 properties.toolType = mExternalStylusState.toolType;
1651 }
1652 }
1653}
1654
1655bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001656 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001657 return false;
1658 }
1659
1660 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1661 state.rawPointerData.pointerCount != 0;
1662 if (initialDown) {
1663 if (mExternalStylusState.pressure != 0.0f) {
1664#if DEBUG_STYLUS_FUSION
1665 ALOGD("Have both stylus and touch data, beginning fusion");
1666#endif
1667 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1668 } else if (timeout) {
1669#if DEBUG_STYLUS_FUSION
1670 ALOGD("Timeout expired, assuming touch is not a stylus.");
1671#endif
1672 resetExternalStylus();
1673 } else {
1674 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1675 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1676 }
1677#if DEBUG_STYLUS_FUSION
1678 ALOGD("No stylus data but stylus is connected, requesting timeout "
1679 "(%" PRId64 "ms)",
1680 mExternalStylusFusionTimeout);
1681#endif
1682 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1683 return true;
1684 }
1685 }
1686
1687 // Check if the stylus pointer has gone up.
1688 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1689#if DEBUG_STYLUS_FUSION
1690 ALOGD("Stylus pointer is going up");
1691#endif
1692 mExternalStylusId = -1;
1693 }
1694
1695 return false;
1696}
1697
1698void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001699 if (mDeviceMode == DeviceMode::POINTER) {
1700 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001701 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1702 }
Michael Wright227c5542020-07-02 18:30:52 +01001703 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001704 if (mExternalStylusFusionTimeout < when) {
1705 processRawTouches(true /*timeout*/);
1706 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1707 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1708 }
1709 }
1710}
1711
1712void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1713 mExternalStylusState.copyFrom(state);
1714 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1715 // We're either in the middle of a fused stream of data or we're waiting on data before
1716 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1717 // data.
1718 mExternalStylusDataPending = true;
1719 processRawTouches(false /*timeout*/);
1720 }
1721}
1722
1723bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1724 // Check for release of a virtual key.
1725 if (mCurrentVirtualKey.down) {
1726 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1727 // Pointer went up while virtual key was down.
1728 mCurrentVirtualKey.down = false;
1729 if (!mCurrentVirtualKey.ignored) {
1730#if DEBUG_VIRTUAL_KEYS
1731 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1732 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1733#endif
1734 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1735 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1736 }
1737 return true;
1738 }
1739
1740 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1741 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1742 const RawPointerData::Pointer& pointer =
1743 mCurrentRawState.rawPointerData.pointerForId(id);
1744 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1745 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1746 // Pointer is still within the space of the virtual key.
1747 return true;
1748 }
1749 }
1750
1751 // Pointer left virtual key area or another pointer also went down.
1752 // Send key cancellation but do not consume the touch yet.
1753 // This is useful when the user swipes through from the virtual key area
1754 // into the main display surface.
1755 mCurrentVirtualKey.down = false;
1756 if (!mCurrentVirtualKey.ignored) {
1757#if DEBUG_VIRTUAL_KEYS
1758 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1759 mCurrentVirtualKey.scanCode);
1760#endif
1761 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1762 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1763 AKEY_EVENT_FLAG_CANCELED);
1764 }
1765 }
1766
1767 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1768 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1769 // Pointer just went down. Check for virtual key press or off-screen touches.
1770 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1771 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001772 // Exclude unscaled device for inside surface checking.
1773 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001774 // If exactly one pointer went down, check for virtual key hit.
1775 // Otherwise we will drop the entire stroke.
1776 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1777 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1778 if (virtualKey) {
1779 mCurrentVirtualKey.down = true;
1780 mCurrentVirtualKey.downTime = when;
1781 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1782 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1783 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001784 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1785 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001786
1787 if (!mCurrentVirtualKey.ignored) {
1788#if DEBUG_VIRTUAL_KEYS
1789 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1790 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1791#endif
1792 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1793 AKEY_EVENT_FLAG_FROM_SYSTEM |
1794 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1795 }
1796 }
1797 }
1798 return true;
1799 }
1800 }
1801
1802 // Disable all virtual key touches that happen within a short time interval of the
1803 // most recent touch within the screen area. The idea is to filter out stray
1804 // virtual key presses when interacting with the touch screen.
1805 //
1806 // Problems we're trying to solve:
1807 //
1808 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1809 // virtual key area that is implemented by a separate touch panel and accidentally
1810 // triggers a virtual key.
1811 //
1812 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1813 // area and accidentally triggers a virtual key. This often happens when virtual keys
1814 // are layed out below the screen near to where the on screen keyboard's space bar
1815 // is displayed.
1816 if (mConfig.virtualKeyQuietTime > 0 &&
1817 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001818 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001819 }
1820 return false;
1821}
1822
1823void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1824 int32_t keyEventAction, int32_t keyEventFlags) {
1825 int32_t keyCode = mCurrentVirtualKey.keyCode;
1826 int32_t scanCode = mCurrentVirtualKey.scanCode;
1827 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001828 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001829 policyFlags |= POLICY_FLAG_VIRTUAL;
1830
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06001831 getContext()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
1832 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode,
1833 metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001834}
1835
1836void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1837 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1838 if (!currentIdBits.isEmpty()) {
1839 int32_t metaState = getContext()->getGlobalMetaState();
1840 int32_t buttonState = mCurrentCookedState.buttonState;
1841 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1842 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1843 mCurrentCookedState.cookedPointerData.pointerProperties,
1844 mCurrentCookedState.cookedPointerData.pointerCoords,
1845 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1846 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1847 mCurrentMotionAborted = true;
1848 }
1849}
1850
1851void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1852 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1853 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1854 int32_t metaState = getContext()->getGlobalMetaState();
1855 int32_t buttonState = mCurrentCookedState.buttonState;
1856
1857 if (currentIdBits == lastIdBits) {
1858 if (!currentIdBits.isEmpty()) {
1859 // No pointer id changes so this is a move event.
1860 // The listener takes care of batching moves so we don't have to deal with that here.
1861 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1862 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1863 mCurrentCookedState.cookedPointerData.pointerProperties,
1864 mCurrentCookedState.cookedPointerData.pointerCoords,
1865 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1866 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1867 }
1868 } else {
1869 // There may be pointers going up and pointers going down and pointers moving
1870 // all at the same time.
1871 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1872 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1873 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1874 BitSet32 dispatchedIdBits(lastIdBits.value);
1875
1876 // Update last coordinates of pointers that have moved so that we observe the new
1877 // pointer positions at the same time as other pointers that have just gone up.
1878 bool moveNeeded =
1879 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1880 mCurrentCookedState.cookedPointerData.pointerCoords,
1881 mCurrentCookedState.cookedPointerData.idToIndex,
1882 mLastCookedState.cookedPointerData.pointerProperties,
1883 mLastCookedState.cookedPointerData.pointerCoords,
1884 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1885 if (buttonState != mLastCookedState.buttonState) {
1886 moveNeeded = true;
1887 }
1888
1889 // Dispatch pointer up events.
1890 while (!upIdBits.isEmpty()) {
1891 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001892 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001893 if (isCanceled) {
1894 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1895 }
arthurhungcc7f9802020-04-30 17:55:40 +08001896 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1897 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001898 mLastCookedState.cookedPointerData.pointerProperties,
1899 mLastCookedState.cookedPointerData.pointerCoords,
1900 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1901 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1902 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001903 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001904 }
1905
1906 // Dispatch move events if any of the remaining pointers moved from their old locations.
1907 // Although applications receive new locations as part of individual pointer up
1908 // events, they do not generally handle them except when presented in a move event.
1909 if (moveNeeded && !moveIdBits.isEmpty()) {
1910 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1911 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1912 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1913 mCurrentCookedState.cookedPointerData.pointerCoords,
1914 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1915 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1916 }
1917
1918 // Dispatch pointer down events using the new pointer locations.
1919 while (!downIdBits.isEmpty()) {
1920 uint32_t downId = downIdBits.clearFirstMarkedBit();
1921 dispatchedIdBits.markBit(downId);
1922
1923 if (dispatchedIdBits.count() == 1) {
1924 // First pointer is going down. Set down time.
1925 mDownTime = when;
1926 }
1927
1928 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1929 metaState, buttonState, 0,
1930 mCurrentCookedState.cookedPointerData.pointerProperties,
1931 mCurrentCookedState.cookedPointerData.pointerCoords,
1932 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1933 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1934 }
1935 }
1936}
1937
1938void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1939 if (mSentHoverEnter &&
1940 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1941 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1942 int32_t metaState = getContext()->getGlobalMetaState();
1943 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1944 mLastCookedState.buttonState, 0,
1945 mLastCookedState.cookedPointerData.pointerProperties,
1946 mLastCookedState.cookedPointerData.pointerCoords,
1947 mLastCookedState.cookedPointerData.idToIndex,
1948 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1949 mOrientedYPrecision, mDownTime);
1950 mSentHoverEnter = false;
1951 }
1952}
1953
1954void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1955 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1956 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1957 int32_t metaState = getContext()->getGlobalMetaState();
1958 if (!mSentHoverEnter) {
1959 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1960 metaState, mCurrentRawState.buttonState, 0,
1961 mCurrentCookedState.cookedPointerData.pointerProperties,
1962 mCurrentCookedState.cookedPointerData.pointerCoords,
1963 mCurrentCookedState.cookedPointerData.idToIndex,
1964 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1965 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1966 mSentHoverEnter = true;
1967 }
1968
1969 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1970 mCurrentRawState.buttonState, 0,
1971 mCurrentCookedState.cookedPointerData.pointerProperties,
1972 mCurrentCookedState.cookedPointerData.pointerCoords,
1973 mCurrentCookedState.cookedPointerData.idToIndex,
1974 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1975 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1976 }
1977}
1978
1979void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1980 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1981 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1982 const int32_t metaState = getContext()->getGlobalMetaState();
1983 int32_t buttonState = mLastCookedState.buttonState;
1984 while (!releasedButtons.isEmpty()) {
1985 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
1986 buttonState &= ~actionButton;
1987 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1988 actionButton, 0, metaState, buttonState, 0,
1989 mCurrentCookedState.cookedPointerData.pointerProperties,
1990 mCurrentCookedState.cookedPointerData.pointerCoords,
1991 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
1992 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1993 }
1994}
1995
1996void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
1997 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
1998 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
1999 const int32_t metaState = getContext()->getGlobalMetaState();
2000 int32_t buttonState = mLastCookedState.buttonState;
2001 while (!pressedButtons.isEmpty()) {
2002 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2003 buttonState |= actionButton;
2004 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2005 0, metaState, buttonState, 0,
2006 mCurrentCookedState.cookedPointerData.pointerProperties,
2007 mCurrentCookedState.cookedPointerData.pointerCoords,
2008 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2009 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2010 }
2011}
2012
2013const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2014 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2015 return cookedPointerData.touchingIdBits;
2016 }
2017 return cookedPointerData.hoveringIdBits;
2018}
2019
2020void TouchInputMapper::cookPointerData() {
2021 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2022
2023 mCurrentCookedState.cookedPointerData.clear();
2024 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2025 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2026 mCurrentRawState.rawPointerData.hoveringIdBits;
2027 mCurrentCookedState.cookedPointerData.touchingIdBits =
2028 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002029 mCurrentCookedState.cookedPointerData.canceledIdBits =
2030 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002031
2032 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2033 mCurrentCookedState.buttonState = 0;
2034 } else {
2035 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2036 }
2037
2038 // Walk through the the active pointers and map device coordinates onto
2039 // surface coordinates and adjust for display orientation.
2040 for (uint32_t i = 0; i < currentPointerCount; i++) {
2041 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2042
2043 // Size
2044 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2045 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002046 case Calibration::SizeCalibration::GEOMETRIC:
2047 case Calibration::SizeCalibration::DIAMETER:
2048 case Calibration::SizeCalibration::BOX:
2049 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002050 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2051 touchMajor = in.touchMajor;
2052 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2053 toolMajor = in.toolMajor;
2054 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2055 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2056 : in.touchMajor;
2057 } else if (mRawPointerAxes.touchMajor.valid) {
2058 toolMajor = touchMajor = in.touchMajor;
2059 toolMinor = touchMinor =
2060 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2061 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2062 : in.touchMajor;
2063 } else if (mRawPointerAxes.toolMajor.valid) {
2064 touchMajor = toolMajor = in.toolMajor;
2065 touchMinor = toolMinor =
2066 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2067 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2068 : in.toolMajor;
2069 } else {
2070 ALOG_ASSERT(false,
2071 "No touch or tool axes. "
2072 "Size calibration should have been resolved to NONE.");
2073 touchMajor = 0;
2074 touchMinor = 0;
2075 toolMajor = 0;
2076 toolMinor = 0;
2077 size = 0;
2078 }
2079
2080 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2081 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2082 if (touchingCount > 1) {
2083 touchMajor /= touchingCount;
2084 touchMinor /= touchingCount;
2085 toolMajor /= touchingCount;
2086 toolMinor /= touchingCount;
2087 size /= touchingCount;
2088 }
2089 }
2090
Michael Wright227c5542020-07-02 18:30:52 +01002091 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002092 touchMajor *= mGeometricScale;
2093 touchMinor *= mGeometricScale;
2094 toolMajor *= mGeometricScale;
2095 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002096 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002097 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2098 touchMinor = touchMajor;
2099 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2100 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002101 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002102 touchMinor = touchMajor;
2103 toolMinor = toolMajor;
2104 }
2105
2106 mCalibration.applySizeScaleAndBias(&touchMajor);
2107 mCalibration.applySizeScaleAndBias(&touchMinor);
2108 mCalibration.applySizeScaleAndBias(&toolMajor);
2109 mCalibration.applySizeScaleAndBias(&toolMinor);
2110 size *= mSizeScale;
2111 break;
2112 default:
2113 touchMajor = 0;
2114 touchMinor = 0;
2115 toolMajor = 0;
2116 toolMinor = 0;
2117 size = 0;
2118 break;
2119 }
2120
2121 // Pressure
2122 float pressure;
2123 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002124 case Calibration::PressureCalibration::PHYSICAL:
2125 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002126 pressure = in.pressure * mPressureScale;
2127 break;
2128 default:
2129 pressure = in.isHovering ? 0 : 1;
2130 break;
2131 }
2132
2133 // Tilt and Orientation
2134 float tilt;
2135 float orientation;
2136 if (mHaveTilt) {
2137 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2138 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2139 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2140 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2141 } else {
2142 tilt = 0;
2143
2144 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002145 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002146 orientation = in.orientation * mOrientationScale;
2147 break;
Michael Wright227c5542020-07-02 18:30:52 +01002148 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002149 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2150 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2151 if (c1 != 0 || c2 != 0) {
2152 orientation = atan2f(c1, c2) * 0.5f;
2153 float confidence = hypotf(c1, c2);
2154 float scale = 1.0f + confidence / 16.0f;
2155 touchMajor *= scale;
2156 touchMinor /= scale;
2157 toolMajor *= scale;
2158 toolMinor /= scale;
2159 } else {
2160 orientation = 0;
2161 }
2162 break;
2163 }
2164 default:
2165 orientation = 0;
2166 }
2167 }
2168
2169 // Distance
2170 float distance;
2171 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002172 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002173 distance = in.distance * mDistanceScale;
2174 break;
2175 default:
2176 distance = 0;
2177 }
2178
2179 // Coverage
2180 int32_t rawLeft, rawTop, rawRight, rawBottom;
2181 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002182 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002183 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2184 rawRight = in.toolMinor & 0x0000ffff;
2185 rawBottom = in.toolMajor & 0x0000ffff;
2186 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2187 break;
2188 default:
2189 rawLeft = rawTop = rawRight = rawBottom = 0;
2190 break;
2191 }
2192
2193 // Adjust X,Y coords for device calibration
2194 // TODO: Adjust coverage coords?
2195 float xTransformed = in.x, yTransformed = in.y;
2196 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002197 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002198
2199 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002200 float left, top, right, bottom;
2201
2202 switch (mSurfaceOrientation) {
2203 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002204 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2205 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2206 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2207 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2208 orientation -= M_PI_2;
2209 if (mOrientedRanges.haveOrientation &&
2210 orientation < mOrientedRanges.orientation.min) {
2211 orientation +=
2212 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2213 }
2214 break;
2215 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002216 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2217 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2218 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2219 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2220 orientation -= M_PI;
2221 if (mOrientedRanges.haveOrientation &&
2222 orientation < mOrientedRanges.orientation.min) {
2223 orientation +=
2224 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2225 }
2226 break;
2227 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002228 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2229 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2230 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2231 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2232 orientation += M_PI_2;
2233 if (mOrientedRanges.haveOrientation &&
2234 orientation > mOrientedRanges.orientation.max) {
2235 orientation -=
2236 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2237 }
2238 break;
2239 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002240 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2241 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2242 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2243 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2244 break;
2245 }
2246
2247 // Write output coords.
2248 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2249 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002250 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2251 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002252 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2253 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2254 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2255 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2256 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2257 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2258 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002259 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002260 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2261 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2262 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2263 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2264 } else {
2265 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2266 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2267 }
2268
Chris Ye364fdb52020-08-05 15:07:56 -07002269 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002270 uint32_t id = in.id;
2271 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2272 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2273 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2274 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2275 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2276 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2277 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2278 }
2279
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002280 // Write output properties.
2281 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002282 properties.clear();
2283 properties.id = id;
2284 properties.toolType = in.toolType;
2285
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002286 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002287 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002288 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002289 }
2290}
2291
2292void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2293 PointerUsage pointerUsage) {
2294 if (pointerUsage != mPointerUsage) {
2295 abortPointerUsage(when, policyFlags);
2296 mPointerUsage = pointerUsage;
2297 }
2298
2299 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002300 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002301 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2302 break;
Michael Wright227c5542020-07-02 18:30:52 +01002303 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002304 dispatchPointerStylus(when, policyFlags);
2305 break;
Michael Wright227c5542020-07-02 18:30:52 +01002306 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002307 dispatchPointerMouse(when, policyFlags);
2308 break;
Michael Wright227c5542020-07-02 18:30:52 +01002309 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002310 break;
2311 }
2312}
2313
2314void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2315 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002316 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317 abortPointerGestures(when, policyFlags);
2318 break;
Michael Wright227c5542020-07-02 18:30:52 +01002319 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 abortPointerStylus(when, policyFlags);
2321 break;
Michael Wright227c5542020-07-02 18:30:52 +01002322 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323 abortPointerMouse(when, policyFlags);
2324 break;
Michael Wright227c5542020-07-02 18:30:52 +01002325 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002326 break;
2327 }
2328
Michael Wright227c5542020-07-02 18:30:52 +01002329 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002330}
2331
2332void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2333 // Update current gesture coordinates.
2334 bool cancelPreviousGesture, finishPreviousGesture;
2335 bool sendEvents =
2336 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2337 if (!sendEvents) {
2338 return;
2339 }
2340 if (finishPreviousGesture) {
2341 cancelPreviousGesture = false;
2342 }
2343
2344 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002345 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002346 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 if (finishPreviousGesture || cancelPreviousGesture) {
2348 mPointerController->clearSpots();
2349 }
2350
Michael Wright227c5542020-07-02 18:30:52 +01002351 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2353 mPointerGesture.currentGestureIdToIndex,
2354 mPointerGesture.currentGestureIdBits,
2355 mPointerController->getDisplayId());
2356 }
2357 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002358 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 }
2360
2361 // Show or hide the pointer if needed.
2362 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002363 case PointerGesture::Mode::NEUTRAL:
2364 case PointerGesture::Mode::QUIET:
2365 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2366 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002368 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 }
2370 break;
Michael Wright227c5542020-07-02 18:30:52 +01002371 case PointerGesture::Mode::TAP:
2372 case PointerGesture::Mode::TAP_DRAG:
2373 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2374 case PointerGesture::Mode::HOVER:
2375 case PointerGesture::Mode::PRESS:
2376 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 // Unfade the pointer when the current gesture manipulates the
2378 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002379 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 break;
Michael Wright227c5542020-07-02 18:30:52 +01002381 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 // Fade the pointer when the current gesture manipulates a different
2383 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002384 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002385 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002386 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002387 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 }
2389 break;
2390 }
2391
2392 // Send events!
2393 int32_t metaState = getContext()->getGlobalMetaState();
2394 int32_t buttonState = mCurrentCookedState.buttonState;
2395
2396 // Update last coordinates of pointers that have moved so that we observe the new
2397 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002398 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2399 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2400 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2401 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2402 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2403 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 bool moveNeeded = false;
2405 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2406 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2407 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2408 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2409 mPointerGesture.lastGestureIdBits.value);
2410 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2411 mPointerGesture.currentGestureCoords,
2412 mPointerGesture.currentGestureIdToIndex,
2413 mPointerGesture.lastGestureProperties,
2414 mPointerGesture.lastGestureCoords,
2415 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2416 if (buttonState != mLastCookedState.buttonState) {
2417 moveNeeded = true;
2418 }
2419 }
2420
2421 // Send motion events for all pointers that went up or were canceled.
2422 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2423 if (!dispatchedGestureIdBits.isEmpty()) {
2424 if (cancelPreviousGesture) {
2425 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2426 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2427 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2428 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2429 mPointerGesture.downTime);
2430
2431 dispatchedGestureIdBits.clear();
2432 } else {
2433 BitSet32 upGestureIdBits;
2434 if (finishPreviousGesture) {
2435 upGestureIdBits = dispatchedGestureIdBits;
2436 } else {
2437 upGestureIdBits.value =
2438 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2439 }
2440 while (!upGestureIdBits.isEmpty()) {
2441 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2442
2443 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2444 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2445 mPointerGesture.lastGestureProperties,
2446 mPointerGesture.lastGestureCoords,
2447 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2448 0, mPointerGesture.downTime);
2449
2450 dispatchedGestureIdBits.clearBit(id);
2451 }
2452 }
2453 }
2454
2455 // Send motion events for all pointers that moved.
2456 if (moveNeeded) {
2457 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2458 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2459 mPointerGesture.currentGestureProperties,
2460 mPointerGesture.currentGestureCoords,
2461 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2462 mPointerGesture.downTime);
2463 }
2464
2465 // Send motion events for all pointers that went down.
2466 if (down) {
2467 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2468 ~dispatchedGestureIdBits.value);
2469 while (!downGestureIdBits.isEmpty()) {
2470 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2471 dispatchedGestureIdBits.markBit(id);
2472
2473 if (dispatchedGestureIdBits.count() == 1) {
2474 mPointerGesture.downTime = when;
2475 }
2476
2477 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2478 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2479 mPointerGesture.currentGestureCoords,
2480 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2481 0, mPointerGesture.downTime);
2482 }
2483 }
2484
2485 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002486 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002487 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2488 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2489 mPointerGesture.currentGestureProperties,
2490 mPointerGesture.currentGestureCoords,
2491 mPointerGesture.currentGestureIdToIndex,
2492 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2493 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2494 // Synthesize a hover move event after all pointers go up to indicate that
2495 // the pointer is hovering again even if the user is not currently touching
2496 // the touch pad. This ensures that a view will receive a fresh hover enter
2497 // event after a tap.
2498 float x, y;
2499 mPointerController->getPosition(&x, &y);
2500
2501 PointerProperties pointerProperties;
2502 pointerProperties.clear();
2503 pointerProperties.id = 0;
2504 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2505
2506 PointerCoords pointerCoords;
2507 pointerCoords.clear();
2508 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2509 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2510
2511 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06002512 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
2513 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState,
2514 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
2515 &pointerProperties, &pointerCoords, 0, 0, x, y,
2516 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002517 }
2518
2519 // Update state.
2520 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2521 if (!down) {
2522 mPointerGesture.lastGestureIdBits.clear();
2523 } else {
2524 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2525 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2526 uint32_t id = idBits.clearFirstMarkedBit();
2527 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2528 mPointerGesture.lastGestureProperties[index].copyFrom(
2529 mPointerGesture.currentGestureProperties[index]);
2530 mPointerGesture.lastGestureCoords[index].copyFrom(
2531 mPointerGesture.currentGestureCoords[index]);
2532 mPointerGesture.lastGestureIdToIndex[id] = index;
2533 }
2534 }
2535}
2536
2537void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2538 // Cancel previously dispatches pointers.
2539 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2540 int32_t metaState = getContext()->getGlobalMetaState();
2541 int32_t buttonState = mCurrentRawState.buttonState;
2542 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2543 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2544 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2545 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2546 0, 0, mPointerGesture.downTime);
2547 }
2548
2549 // Reset the current pointer gesture.
2550 mPointerGesture.reset();
2551 mPointerVelocityControl.reset();
2552
2553 // Remove any current spots.
2554 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002555 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002556 mPointerController->clearSpots();
2557 }
2558}
2559
2560bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2561 bool* outFinishPreviousGesture, bool isTimeout) {
2562 *outCancelPreviousGesture = false;
2563 *outFinishPreviousGesture = false;
2564
2565 // Handle TAP timeout.
2566 if (isTimeout) {
2567#if DEBUG_GESTURES
2568 ALOGD("Gestures: Processing timeout");
2569#endif
2570
Michael Wright227c5542020-07-02 18:30:52 +01002571 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002572 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2573 // The tap/drag timeout has not yet expired.
2574 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2575 mConfig.pointerGestureTapDragInterval);
2576 } else {
2577 // The tap is finished.
2578#if DEBUG_GESTURES
2579 ALOGD("Gestures: TAP finished");
2580#endif
2581 *outFinishPreviousGesture = true;
2582
2583 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002584 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002585 mPointerGesture.currentGestureIdBits.clear();
2586
2587 mPointerVelocityControl.reset();
2588 return true;
2589 }
2590 }
2591
2592 // We did not handle this timeout.
2593 return false;
2594 }
2595
2596 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2597 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2598
2599 // Update the velocity tracker.
2600 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002601 std::vector<VelocityTracker::Position> positions;
2602 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002603 uint32_t id = idBits.clearFirstMarkedBit();
2604 const RawPointerData::Pointer& pointer =
2605 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002606 float x = pointer.x * mPointerXMovementScale;
2607 float y = pointer.y * mPointerYMovementScale;
2608 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002609 }
2610 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2611 positions);
2612 }
2613
2614 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2615 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002616 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2617 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2618 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002619 mPointerGesture.resetTap();
2620 }
2621
2622 // Pick a new active touch id if needed.
2623 // Choose an arbitrary pointer that just went down, if there is one.
2624 // Otherwise choose an arbitrary remaining pointer.
2625 // This guarantees we always have an active touch id when there is at least one pointer.
2626 // We keep the same active touch id for as long as possible.
2627 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2628 int32_t activeTouchId = lastActiveTouchId;
2629 if (activeTouchId < 0) {
2630 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2631 activeTouchId = mPointerGesture.activeTouchId =
2632 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2633 mPointerGesture.firstTouchTime = when;
2634 }
2635 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2636 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2637 activeTouchId = mPointerGesture.activeTouchId =
2638 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2639 } else {
2640 activeTouchId = mPointerGesture.activeTouchId = -1;
2641 }
2642 }
2643
2644 // Determine whether we are in quiet time.
2645 bool isQuietTime = false;
2646 if (activeTouchId < 0) {
2647 mPointerGesture.resetQuietTime();
2648 } else {
2649 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2650 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002651 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2652 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2653 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002654 currentFingerCount < 2) {
2655 // Enter quiet time when exiting swipe or freeform state.
2656 // This is to prevent accidentally entering the hover state and flinging the
2657 // pointer when finishing a swipe and there is still one pointer left onscreen.
2658 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002659 } else if (mPointerGesture.lastGestureMode ==
2660 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002661 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2662 // Enter quiet time when releasing the button and there are still two or more
2663 // fingers down. This may indicate that one finger was used to press the button
2664 // but it has not gone up yet.
2665 isQuietTime = true;
2666 }
2667 if (isQuietTime) {
2668 mPointerGesture.quietTime = when;
2669 }
2670 }
2671 }
2672
2673 // Switch states based on button and pointer state.
2674 if (isQuietTime) {
2675 // Case 1: Quiet time. (QUIET)
2676#if DEBUG_GESTURES
2677 ALOGD("Gestures: QUIET for next %0.3fms",
2678 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2679#endif
Michael Wright227c5542020-07-02 18:30:52 +01002680 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002681 *outFinishPreviousGesture = true;
2682 }
2683
2684 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002685 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002686 mPointerGesture.currentGestureIdBits.clear();
2687
2688 mPointerVelocityControl.reset();
2689 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2690 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2691 // The pointer follows the active touch point.
2692 // Emit DOWN, MOVE, UP events at the pointer location.
2693 //
2694 // Only the active touch matters; other fingers are ignored. This policy helps
2695 // to handle the case where the user places a second finger on the touch pad
2696 // to apply the necessary force to depress an integrated button below the surface.
2697 // We don't want the second finger to be delivered to applications.
2698 //
2699 // For this to work well, we need to make sure to track the pointer that is really
2700 // active. If the user first puts one finger down to click then adds another
2701 // finger to drag then the active pointer should switch to the finger that is
2702 // being dragged.
2703#if DEBUG_GESTURES
2704 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2705 "currentFingerCount=%d",
2706 activeTouchId, currentFingerCount);
2707#endif
2708 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002709 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002710 *outFinishPreviousGesture = true;
2711 mPointerGesture.activeGestureId = 0;
2712 }
2713
2714 // Switch pointers if needed.
2715 // Find the fastest pointer and follow it.
2716 if (activeTouchId >= 0 && currentFingerCount > 1) {
2717 int32_t bestId = -1;
2718 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2719 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2720 uint32_t id = idBits.clearFirstMarkedBit();
2721 float vx, vy;
2722 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2723 float speed = hypotf(vx, vy);
2724 if (speed > bestSpeed) {
2725 bestId = id;
2726 bestSpeed = speed;
2727 }
2728 }
2729 }
2730 if (bestId >= 0 && bestId != activeTouchId) {
2731 mPointerGesture.activeTouchId = activeTouchId = bestId;
2732#if DEBUG_GESTURES
2733 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2734 "bestId=%d, bestSpeed=%0.3f",
2735 bestId, bestSpeed);
2736#endif
2737 }
2738 }
2739
2740 float deltaX = 0, deltaY = 0;
2741 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2742 const RawPointerData::Pointer& currentPointer =
2743 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2744 const RawPointerData::Pointer& lastPointer =
2745 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2746 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2747 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2748
2749 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2750 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2751
2752 // Move the pointer using a relative motion.
2753 // When using spots, the click will occur at the position of the anchor
2754 // spot and all other spots will move there.
2755 mPointerController->move(deltaX, deltaY);
2756 } else {
2757 mPointerVelocityControl.reset();
2758 }
2759
2760 float x, y;
2761 mPointerController->getPosition(&x, &y);
2762
Michael Wright227c5542020-07-02 18:30:52 +01002763 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002764 mPointerGesture.currentGestureIdBits.clear();
2765 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2766 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2767 mPointerGesture.currentGestureProperties[0].clear();
2768 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2769 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2770 mPointerGesture.currentGestureCoords[0].clear();
2771 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2772 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2773 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2774 } else if (currentFingerCount == 0) {
2775 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002776 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002777 *outFinishPreviousGesture = true;
2778 }
2779
2780 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2781 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2782 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002783 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2784 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002785 lastFingerCount == 1) {
2786 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2787 float x, y;
2788 mPointerController->getPosition(&x, &y);
2789 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2790 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2791#if DEBUG_GESTURES
2792 ALOGD("Gestures: TAP");
2793#endif
2794
2795 mPointerGesture.tapUpTime = when;
2796 getContext()->requestTimeoutAtTime(when +
2797 mConfig.pointerGestureTapDragInterval);
2798
2799 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002800 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002801 mPointerGesture.currentGestureIdBits.clear();
2802 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2803 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2804 mPointerGesture.currentGestureProperties[0].clear();
2805 mPointerGesture.currentGestureProperties[0].id =
2806 mPointerGesture.activeGestureId;
2807 mPointerGesture.currentGestureProperties[0].toolType =
2808 AMOTION_EVENT_TOOL_TYPE_FINGER;
2809 mPointerGesture.currentGestureCoords[0].clear();
2810 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2811 mPointerGesture.tapX);
2812 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2813 mPointerGesture.tapY);
2814 mPointerGesture.currentGestureCoords[0]
2815 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2816
2817 tapped = true;
2818 } else {
2819#if DEBUG_GESTURES
2820 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2821 y - mPointerGesture.tapY);
2822#endif
2823 }
2824 } else {
2825#if DEBUG_GESTURES
2826 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2827 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2828 (when - mPointerGesture.tapDownTime) * 0.000001f);
2829 } else {
2830 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2831 }
2832#endif
2833 }
2834 }
2835
2836 mPointerVelocityControl.reset();
2837
2838 if (!tapped) {
2839#if DEBUG_GESTURES
2840 ALOGD("Gestures: NEUTRAL");
2841#endif
2842 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002843 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002844 mPointerGesture.currentGestureIdBits.clear();
2845 }
2846 } else if (currentFingerCount == 1) {
2847 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2848 // The pointer follows the active touch point.
2849 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2850 // When in TAP_DRAG, emit MOVE events at the pointer location.
2851 ALOG_ASSERT(activeTouchId >= 0);
2852
Michael Wright227c5542020-07-02 18:30:52 +01002853 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2854 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2856 float x, y;
2857 mPointerController->getPosition(&x, &y);
2858 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2859 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002860 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002861 } else {
2862#if DEBUG_GESTURES
2863 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2864 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2865#endif
2866 }
2867 } else {
2868#if DEBUG_GESTURES
2869 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2870 (when - mPointerGesture.tapUpTime) * 0.000001f);
2871#endif
2872 }
Michael Wright227c5542020-07-02 18:30:52 +01002873 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2874 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 }
2876
2877 float deltaX = 0, deltaY = 0;
2878 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2879 const RawPointerData::Pointer& currentPointer =
2880 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2881 const RawPointerData::Pointer& lastPointer =
2882 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2883 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2884 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2885
2886 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2887 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2888
2889 // Move the pointer using a relative motion.
2890 // When using spots, the hover or drag will occur at the position of the anchor spot.
2891 mPointerController->move(deltaX, deltaY);
2892 } else {
2893 mPointerVelocityControl.reset();
2894 }
2895
2896 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002897 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002898#if DEBUG_GESTURES
2899 ALOGD("Gestures: TAP_DRAG");
2900#endif
2901 down = true;
2902 } else {
2903#if DEBUG_GESTURES
2904 ALOGD("Gestures: HOVER");
2905#endif
Michael Wright227c5542020-07-02 18:30:52 +01002906 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 *outFinishPreviousGesture = true;
2908 }
2909 mPointerGesture.activeGestureId = 0;
2910 down = false;
2911 }
2912
2913 float x, y;
2914 mPointerController->getPosition(&x, &y);
2915
2916 mPointerGesture.currentGestureIdBits.clear();
2917 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2918 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2919 mPointerGesture.currentGestureProperties[0].clear();
2920 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2921 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2922 mPointerGesture.currentGestureCoords[0].clear();
2923 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2924 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2925 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2926 down ? 1.0f : 0.0f);
2927
2928 if (lastFingerCount == 0 && currentFingerCount != 0) {
2929 mPointerGesture.resetTap();
2930 mPointerGesture.tapDownTime = when;
2931 mPointerGesture.tapX = x;
2932 mPointerGesture.tapY = y;
2933 }
2934 } else {
2935 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2936 // We need to provide feedback for each finger that goes down so we cannot wait
2937 // for the fingers to move before deciding what to do.
2938 //
2939 // The ambiguous case is deciding what to do when there are two fingers down but they
2940 // have not moved enough to determine whether they are part of a drag or part of a
2941 // freeform gesture, or just a press or long-press at the pointer location.
2942 //
2943 // When there are two fingers we start with the PRESS hypothesis and we generate a
2944 // down at the pointer location.
2945 //
2946 // When the two fingers move enough or when additional fingers are added, we make
2947 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2948 ALOG_ASSERT(activeTouchId >= 0);
2949
2950 bool settled = when >=
2951 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002952 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2953 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2954 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002955 *outFinishPreviousGesture = true;
2956 } else if (!settled && currentFingerCount > lastFingerCount) {
2957 // Additional pointers have gone down but not yet settled.
2958 // Reset the gesture.
2959#if DEBUG_GESTURES
2960 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2961 "settle time remaining %0.3fms",
2962 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2963 when) * 0.000001f);
2964#endif
2965 *outCancelPreviousGesture = true;
2966 } else {
2967 // Continue previous gesture.
2968 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2969 }
2970
2971 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002972 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 mPointerGesture.activeGestureId = 0;
2974 mPointerGesture.referenceIdBits.clear();
2975 mPointerVelocityControl.reset();
2976
2977 // Use the centroid and pointer location as the reference points for the gesture.
2978#if DEBUG_GESTURES
2979 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2980 "settle time remaining %0.3fms",
2981 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2982 when) * 0.000001f);
2983#endif
2984 mCurrentRawState.rawPointerData
2985 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
2986 &mPointerGesture.referenceTouchY);
2987 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
2988 &mPointerGesture.referenceGestureY);
2989 }
2990
2991 // Clear the reference deltas for fingers not yet included in the reference calculation.
2992 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
2993 ~mPointerGesture.referenceIdBits.value);
2994 !idBits.isEmpty();) {
2995 uint32_t id = idBits.clearFirstMarkedBit();
2996 mPointerGesture.referenceDeltas[id].dx = 0;
2997 mPointerGesture.referenceDeltas[id].dy = 0;
2998 }
2999 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3000
3001 // Add delta for all fingers and calculate a common movement delta.
3002 float commonDeltaX = 0, commonDeltaY = 0;
3003 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3004 mCurrentCookedState.fingerIdBits.value);
3005 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3006 bool first = (idBits == commonIdBits);
3007 uint32_t id = idBits.clearFirstMarkedBit();
3008 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3009 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3010 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3011 delta.dx += cpd.x - lpd.x;
3012 delta.dy += cpd.y - lpd.y;
3013
3014 if (first) {
3015 commonDeltaX = delta.dx;
3016 commonDeltaY = delta.dy;
3017 } else {
3018 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3019 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3020 }
3021 }
3022
3023 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003024 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003025 float dist[MAX_POINTER_ID + 1];
3026 int32_t distOverThreshold = 0;
3027 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3028 uint32_t id = idBits.clearFirstMarkedBit();
3029 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3030 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3031 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3032 distOverThreshold += 1;
3033 }
3034 }
3035
3036 // Only transition when at least two pointers have moved further than
3037 // the minimum distance threshold.
3038 if (distOverThreshold >= 2) {
3039 if (currentFingerCount > 2) {
3040 // There are more than two pointers, switch to FREEFORM.
3041#if DEBUG_GESTURES
3042 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3043 currentFingerCount);
3044#endif
3045 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003046 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047 } else {
3048 // There are exactly two pointers.
3049 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3050 uint32_t id1 = idBits.clearFirstMarkedBit();
3051 uint32_t id2 = idBits.firstMarkedBit();
3052 const RawPointerData::Pointer& p1 =
3053 mCurrentRawState.rawPointerData.pointerForId(id1);
3054 const RawPointerData::Pointer& p2 =
3055 mCurrentRawState.rawPointerData.pointerForId(id2);
3056 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3057 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3058 // There are two pointers but they are too far apart for a SWIPE,
3059 // switch to FREEFORM.
3060#if DEBUG_GESTURES
3061 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3062 mutualDistance, mPointerGestureMaxSwipeWidth);
3063#endif
3064 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003065 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003066 } else {
3067 // There are two pointers. Wait for both pointers to start moving
3068 // before deciding whether this is a SWIPE or FREEFORM gesture.
3069 float dist1 = dist[id1];
3070 float dist2 = dist[id2];
3071 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3072 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3073 // Calculate the dot product of the displacement vectors.
3074 // When the vectors are oriented in approximately the same direction,
3075 // the angle betweeen them is near zero and the cosine of the angle
3076 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3077 // mag(v2).
3078 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3079 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3080 float dx1 = delta1.dx * mPointerXZoomScale;
3081 float dy1 = delta1.dy * mPointerYZoomScale;
3082 float dx2 = delta2.dx * mPointerXZoomScale;
3083 float dy2 = delta2.dy * mPointerYZoomScale;
3084 float dot = dx1 * dx2 + dy1 * dy2;
3085 float cosine = dot / (dist1 * dist2); // denominator always > 0
3086 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3087 // Pointers are moving in the same direction. Switch to SWIPE.
3088#if DEBUG_GESTURES
3089 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3090 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3091 "cosine %0.3f >= %0.3f",
3092 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3093 mConfig.pointerGestureMultitouchMinDistance, cosine,
3094 mConfig.pointerGestureSwipeTransitionAngleCosine);
3095#endif
Michael Wright227c5542020-07-02 18:30:52 +01003096 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003097 } else {
3098 // Pointers are moving in different directions. Switch to FREEFORM.
3099#if DEBUG_GESTURES
3100 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3101 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3102 "cosine %0.3f < %0.3f",
3103 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3104 mConfig.pointerGestureMultitouchMinDistance, cosine,
3105 mConfig.pointerGestureSwipeTransitionAngleCosine);
3106#endif
3107 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003108 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003109 }
3110 }
3111 }
3112 }
3113 }
Michael Wright227c5542020-07-02 18:30:52 +01003114 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003115 // Switch from SWIPE to FREEFORM if additional pointers go down.
3116 // Cancel previous gesture.
3117 if (currentFingerCount > 2) {
3118#if DEBUG_GESTURES
3119 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3120 currentFingerCount);
3121#endif
3122 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003123 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003124 }
3125 }
3126
3127 // Move the reference points based on the overall group motion of the fingers
3128 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003129 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003130 (commonDeltaX || commonDeltaY)) {
3131 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3132 uint32_t id = idBits.clearFirstMarkedBit();
3133 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3134 delta.dx = 0;
3135 delta.dy = 0;
3136 }
3137
3138 mPointerGesture.referenceTouchX += commonDeltaX;
3139 mPointerGesture.referenceTouchY += commonDeltaY;
3140
3141 commonDeltaX *= mPointerXMovementScale;
3142 commonDeltaY *= mPointerYMovementScale;
3143
3144 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3145 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3146
3147 mPointerGesture.referenceGestureX += commonDeltaX;
3148 mPointerGesture.referenceGestureY += commonDeltaY;
3149 }
3150
3151 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003152 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3153 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003154 // PRESS or SWIPE mode.
3155#if DEBUG_GESTURES
3156 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3157 "activeGestureId=%d, currentTouchPointerCount=%d",
3158 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3159#endif
3160 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3161
3162 mPointerGesture.currentGestureIdBits.clear();
3163 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3164 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3165 mPointerGesture.currentGestureProperties[0].clear();
3166 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3167 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3168 mPointerGesture.currentGestureCoords[0].clear();
3169 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3170 mPointerGesture.referenceGestureX);
3171 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3172 mPointerGesture.referenceGestureY);
3173 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003174 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003175 // FREEFORM mode.
3176#if DEBUG_GESTURES
3177 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3178 "activeGestureId=%d, currentTouchPointerCount=%d",
3179 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3180#endif
3181 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3182
3183 mPointerGesture.currentGestureIdBits.clear();
3184
3185 BitSet32 mappedTouchIdBits;
3186 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003187 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003188 // Initially, assign the active gesture id to the active touch point
3189 // if there is one. No other touch id bits are mapped yet.
3190 if (!*outCancelPreviousGesture) {
3191 mappedTouchIdBits.markBit(activeTouchId);
3192 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3193 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3194 mPointerGesture.activeGestureId;
3195 } else {
3196 mPointerGesture.activeGestureId = -1;
3197 }
3198 } else {
3199 // Otherwise, assume we mapped all touches from the previous frame.
3200 // Reuse all mappings that are still applicable.
3201 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3202 mCurrentCookedState.fingerIdBits.value;
3203 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3204
3205 // Check whether we need to choose a new active gesture id because the
3206 // current went went up.
3207 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3208 ~mCurrentCookedState.fingerIdBits.value);
3209 !upTouchIdBits.isEmpty();) {
3210 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3211 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3212 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3213 mPointerGesture.activeGestureId = -1;
3214 break;
3215 }
3216 }
3217 }
3218
3219#if DEBUG_GESTURES
3220 ALOGD("Gestures: FREEFORM follow up "
3221 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3222 "activeGestureId=%d",
3223 mappedTouchIdBits.value, usedGestureIdBits.value,
3224 mPointerGesture.activeGestureId);
3225#endif
3226
3227 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3228 for (uint32_t i = 0; i < currentFingerCount; i++) {
3229 uint32_t touchId = idBits.clearFirstMarkedBit();
3230 uint32_t gestureId;
3231 if (!mappedTouchIdBits.hasBit(touchId)) {
3232 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3233 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3234#if DEBUG_GESTURES
3235 ALOGD("Gestures: FREEFORM "
3236 "new mapping for touch id %d -> gesture id %d",
3237 touchId, gestureId);
3238#endif
3239 } else {
3240 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3241#if DEBUG_GESTURES
3242 ALOGD("Gestures: FREEFORM "
3243 "existing mapping for touch id %d -> gesture id %d",
3244 touchId, gestureId);
3245#endif
3246 }
3247 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3248 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3249
3250 const RawPointerData::Pointer& pointer =
3251 mCurrentRawState.rawPointerData.pointerForId(touchId);
3252 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3253 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3254 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3255
3256 mPointerGesture.currentGestureProperties[i].clear();
3257 mPointerGesture.currentGestureProperties[i].id = gestureId;
3258 mPointerGesture.currentGestureProperties[i].toolType =
3259 AMOTION_EVENT_TOOL_TYPE_FINGER;
3260 mPointerGesture.currentGestureCoords[i].clear();
3261 mPointerGesture.currentGestureCoords[i]
3262 .setAxisValue(AMOTION_EVENT_AXIS_X,
3263 mPointerGesture.referenceGestureX + deltaX);
3264 mPointerGesture.currentGestureCoords[i]
3265 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3266 mPointerGesture.referenceGestureY + deltaY);
3267 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3268 1.0f);
3269 }
3270
3271 if (mPointerGesture.activeGestureId < 0) {
3272 mPointerGesture.activeGestureId =
3273 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3274#if DEBUG_GESTURES
3275 ALOGD("Gestures: FREEFORM new "
3276 "activeGestureId=%d",
3277 mPointerGesture.activeGestureId);
3278#endif
3279 }
3280 }
3281 }
3282
3283 mPointerController->setButtonState(mCurrentRawState.buttonState);
3284
3285#if DEBUG_GESTURES
3286 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3287 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3288 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3289 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3290 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3291 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3292 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3293 uint32_t id = idBits.clearFirstMarkedBit();
3294 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3295 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3296 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3297 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3298 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3299 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3300 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3301 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3302 }
3303 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3304 uint32_t id = idBits.clearFirstMarkedBit();
3305 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3306 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3307 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3308 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3309 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3310 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3311 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3312 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3313 }
3314#endif
3315 return true;
3316}
3317
3318void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3319 mPointerSimple.currentCoords.clear();
3320 mPointerSimple.currentProperties.clear();
3321
3322 bool down, hovering;
3323 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3324 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3325 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3326 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3327 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3328 mPointerController->setPosition(x, y);
3329
3330 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3331 down = !hovering;
3332
3333 mPointerController->getPosition(&x, &y);
3334 mPointerSimple.currentCoords.copyFrom(
3335 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3336 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3337 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3338 mPointerSimple.currentProperties.id = 0;
3339 mPointerSimple.currentProperties.toolType =
3340 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3341 } else {
3342 down = false;
3343 hovering = false;
3344 }
3345
3346 dispatchPointerSimple(when, policyFlags, down, hovering);
3347}
3348
3349void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3350 abortPointerSimple(when, policyFlags);
3351}
3352
3353void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3354 mPointerSimple.currentCoords.clear();
3355 mPointerSimple.currentProperties.clear();
3356
3357 bool down, hovering;
3358 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3359 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3360 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3361 float deltaX = 0, deltaY = 0;
3362 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3363 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3364 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3365 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3366 mPointerXMovementScale;
3367 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3368 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3369 mPointerYMovementScale;
3370
3371 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3372 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3373
3374 mPointerController->move(deltaX, deltaY);
3375 } else {
3376 mPointerVelocityControl.reset();
3377 }
3378
3379 down = isPointerDown(mCurrentRawState.buttonState);
3380 hovering = !down;
3381
3382 float x, y;
3383 mPointerController->getPosition(&x, &y);
3384 mPointerSimple.currentCoords.copyFrom(
3385 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3386 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3387 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3388 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3389 hovering ? 0.0f : 1.0f);
3390 mPointerSimple.currentProperties.id = 0;
3391 mPointerSimple.currentProperties.toolType =
3392 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3393 } else {
3394 mPointerVelocityControl.reset();
3395
3396 down = false;
3397 hovering = false;
3398 }
3399
3400 dispatchPointerSimple(when, policyFlags, down, hovering);
3401}
3402
3403void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3404 abortPointerSimple(when, policyFlags);
3405
3406 mPointerVelocityControl.reset();
3407}
3408
3409void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3410 bool hovering) {
3411 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003412
3413 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003414 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003415 mPointerController->clearSpots();
3416 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003417 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003418 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003419 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003420 }
Garfield Tan9514d782020-11-10 16:37:23 -08003421 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003422
3423 float xCursorPosition;
3424 float yCursorPosition;
3425 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3426
3427 if (mPointerSimple.down && !down) {
3428 mPointerSimple.down = false;
3429
3430 // Send up.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003431 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3432 AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
3433 mLastRawState.buttonState, MotionClassification::NONE,
3434 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3435 &mPointerSimple.lastCoords, mOrientedXPrecision,
3436 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3437 mPointerSimple.downTime,
3438 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003439 }
3440
3441 if (mPointerSimple.hovering && !hovering) {
3442 mPointerSimple.hovering = false;
3443
3444 // Send hover exit.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003445 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3446 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3447 mLastRawState.buttonState, MotionClassification::NONE,
3448 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3449 &mPointerSimple.lastCoords, mOrientedXPrecision,
3450 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3451 mPointerSimple.downTime,
3452 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003453 }
3454
3455 if (down) {
3456 if (!mPointerSimple.down) {
3457 mPointerSimple.down = true;
3458 mPointerSimple.downTime = when;
3459
3460 // Send down.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003461 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3462 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3463 mCurrentRawState.buttonState, MotionClassification::NONE,
3464 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3465 &mPointerSimple.currentProperties,
3466 &mPointerSimple.currentCoords, mOrientedXPrecision,
3467 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3468 mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469 }
3470
3471 // Send move.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003472 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3473 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
3474 mCurrentRawState.buttonState, MotionClassification::NONE,
3475 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3476 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3477 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3478 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003479 }
3480
3481 if (hovering) {
3482 if (!mPointerSimple.hovering) {
3483 mPointerSimple.hovering = true;
3484
3485 // Send hover enter.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003486 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3487 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3488 mCurrentRawState.buttonState, MotionClassification::NONE,
3489 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3490 &mPointerSimple.currentProperties,
3491 &mPointerSimple.currentCoords, mOrientedXPrecision,
3492 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3493 mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003494 }
3495
3496 // Send hover move.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003497 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3498 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3499 mCurrentRawState.buttonState, MotionClassification::NONE,
3500 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3501 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3502 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3503 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003504 }
3505
3506 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3507 float vscroll = mCurrentRawState.rawVScroll;
3508 float hscroll = mCurrentRawState.rawHScroll;
3509 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3510 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3511
3512 // Send scroll.
3513 PointerCoords pointerCoords;
3514 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3515 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3516 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3517
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003518 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3519 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
3520 mCurrentRawState.buttonState, MotionClassification::NONE,
3521 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3522 &mPointerSimple.currentProperties, &pointerCoords,
3523 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3524 yCursorPosition, mPointerSimple.downTime,
3525 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003526 }
3527
3528 // Save state.
3529 if (down || hovering) {
3530 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3531 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3532 } else {
3533 mPointerSimple.reset();
3534 }
3535}
3536
3537void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3538 mPointerSimple.currentCoords.clear();
3539 mPointerSimple.currentProperties.clear();
3540
3541 dispatchPointerSimple(when, policyFlags, false, false);
3542}
3543
3544void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3545 int32_t action, int32_t actionButton, int32_t flags,
3546 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3547 const PointerProperties* properties,
3548 const PointerCoords* coords, const uint32_t* idToIndex,
3549 BitSet32 idBits, int32_t changedId, float xPrecision,
3550 float yPrecision, nsecs_t downTime) {
3551 PointerCoords pointerCoords[MAX_POINTERS];
3552 PointerProperties pointerProperties[MAX_POINTERS];
3553 uint32_t pointerCount = 0;
3554 while (!idBits.isEmpty()) {
3555 uint32_t id = idBits.clearFirstMarkedBit();
3556 uint32_t index = idToIndex[id];
3557 pointerProperties[pointerCount].copyFrom(properties[index]);
3558 pointerCoords[pointerCount].copyFrom(coords[index]);
3559
3560 if (changedId >= 0 && id == uint32_t(changedId)) {
3561 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3562 }
3563
3564 pointerCount += 1;
3565 }
3566
3567 ALOG_ASSERT(pointerCount != 0);
3568
3569 if (changedId >= 0 && pointerCount == 1) {
3570 // Replace initial down and final up action.
3571 // We can compare the action without masking off the changed pointer index
3572 // because we know the index is 0.
3573 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3574 action = AMOTION_EVENT_ACTION_DOWN;
3575 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003576 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3577 action = AMOTION_EVENT_ACTION_CANCEL;
3578 } else {
3579 action = AMOTION_EVENT_ACTION_UP;
3580 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003581 } else {
3582 // Can't happen.
3583 ALOG_ASSERT(false);
3584 }
3585 }
3586 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3587 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003588 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3590 }
3591 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3592 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003593 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003594 std::for_each(frames.begin(), frames.end(),
3595 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003596 getContext()->notifyMotion(when, deviceId, source, displayId, policyFlags, action, actionButton,
3597 flags, metaState, buttonState, MotionClassification::NONE, edgeFlags,
3598 pointerCount, pointerProperties, pointerCoords, xPrecision,
3599 yPrecision, xCursorPosition, yCursorPosition, downTime,
3600 std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003601}
3602
3603bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3604 const PointerCoords* inCoords,
3605 const uint32_t* inIdToIndex,
3606 PointerProperties* outProperties,
3607 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3608 BitSet32 idBits) const {
3609 bool changed = false;
3610 while (!idBits.isEmpty()) {
3611 uint32_t id = idBits.clearFirstMarkedBit();
3612 uint32_t inIndex = inIdToIndex[id];
3613 uint32_t outIndex = outIdToIndex[id];
3614
3615 const PointerProperties& curInProperties = inProperties[inIndex];
3616 const PointerCoords& curInCoords = inCoords[inIndex];
3617 PointerProperties& curOutProperties = outProperties[outIndex];
3618 PointerCoords& curOutCoords = outCoords[outIndex];
3619
3620 if (curInProperties != curOutProperties) {
3621 curOutProperties.copyFrom(curInProperties);
3622 changed = true;
3623 }
3624
3625 if (curInCoords != curOutCoords) {
3626 curOutCoords.copyFrom(curInCoords);
3627 changed = true;
3628 }
3629 }
3630 return changed;
3631}
3632
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003633void TouchInputMapper::cancelTouch(nsecs_t when) {
3634 abortPointerUsage(when, 0 /*policyFlags*/);
3635 abortTouches(when, 0 /* policyFlags*/);
3636}
3637
Arthur Hung4197f6b2020-03-16 15:39:59 +08003638// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003639void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003640 // Scale to surface coordinate.
3641 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3642 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3643
arthurhunga36b28e2020-12-29 20:28:15 +08003644 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3645 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3646
Arthur Hung4197f6b2020-03-16 15:39:59 +08003647 // Rotate to surface coordinate.
3648 // 0 - no swap and reverse.
3649 // 90 - swap x/y and reverse y.
3650 // 180 - reverse x, y.
3651 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003652 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003653 case DISPLAY_ORIENTATION_0:
3654 x = xScaled + mXTranslate;
3655 y = yScaled + mYTranslate;
3656 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003657 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003658 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003659 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003660 break;
3661 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003662 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3663 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003664 break;
3665 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003666 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003667 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003668 break;
3669 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003670 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003671 }
3672}
3673
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003674bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003675 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3676 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3677
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003678 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003679 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003680 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003681 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003682}
3683
3684const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3685 for (const VirtualKey& virtualKey : mVirtualKeys) {
3686#if DEBUG_VIRTUAL_KEYS
3687 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3688 "left=%d, top=%d, right=%d, bottom=%d",
3689 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3690 virtualKey.hitRight, virtualKey.hitBottom);
3691#endif
3692
3693 if (virtualKey.isHit(x, y)) {
3694 return &virtualKey;
3695 }
3696 }
3697
3698 return nullptr;
3699}
3700
3701void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3702 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3703 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3704
3705 current->rawPointerData.clearIdBits();
3706
3707 if (currentPointerCount == 0) {
3708 // No pointers to assign.
3709 return;
3710 }
3711
3712 if (lastPointerCount == 0) {
3713 // All pointers are new.
3714 for (uint32_t i = 0; i < currentPointerCount; i++) {
3715 uint32_t id = i;
3716 current->rawPointerData.pointers[i].id = id;
3717 current->rawPointerData.idToIndex[id] = i;
3718 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3719 }
3720 return;
3721 }
3722
3723 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3724 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3725 // Only one pointer and no change in count so it must have the same id as before.
3726 uint32_t id = last->rawPointerData.pointers[0].id;
3727 current->rawPointerData.pointers[0].id = id;
3728 current->rawPointerData.idToIndex[id] = 0;
3729 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3730 return;
3731 }
3732
3733 // General case.
3734 // We build a heap of squared euclidean distances between current and last pointers
3735 // associated with the current and last pointer indices. Then, we find the best
3736 // match (by distance) for each current pointer.
3737 // The pointers must have the same tool type but it is possible for them to
3738 // transition from hovering to touching or vice-versa while retaining the same id.
3739 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3740
3741 uint32_t heapSize = 0;
3742 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3743 currentPointerIndex++) {
3744 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3745 lastPointerIndex++) {
3746 const RawPointerData::Pointer& currentPointer =
3747 current->rawPointerData.pointers[currentPointerIndex];
3748 const RawPointerData::Pointer& lastPointer =
3749 last->rawPointerData.pointers[lastPointerIndex];
3750 if (currentPointer.toolType == lastPointer.toolType) {
3751 int64_t deltaX = currentPointer.x - lastPointer.x;
3752 int64_t deltaY = currentPointer.y - lastPointer.y;
3753
3754 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3755
3756 // Insert new element into the heap (sift up).
3757 heap[heapSize].currentPointerIndex = currentPointerIndex;
3758 heap[heapSize].lastPointerIndex = lastPointerIndex;
3759 heap[heapSize].distance = distance;
3760 heapSize += 1;
3761 }
3762 }
3763 }
3764
3765 // Heapify
3766 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3767 startIndex -= 1;
3768 for (uint32_t parentIndex = startIndex;;) {
3769 uint32_t childIndex = parentIndex * 2 + 1;
3770 if (childIndex >= heapSize) {
3771 break;
3772 }
3773
3774 if (childIndex + 1 < heapSize &&
3775 heap[childIndex + 1].distance < heap[childIndex].distance) {
3776 childIndex += 1;
3777 }
3778
3779 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3780 break;
3781 }
3782
3783 swap(heap[parentIndex], heap[childIndex]);
3784 parentIndex = childIndex;
3785 }
3786 }
3787
3788#if DEBUG_POINTER_ASSIGNMENT
3789 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3790 for (size_t i = 0; i < heapSize; i++) {
3791 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3792 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3793 }
3794#endif
3795
3796 // Pull matches out by increasing order of distance.
3797 // To avoid reassigning pointers that have already been matched, the loop keeps track
3798 // of which last and current pointers have been matched using the matchedXXXBits variables.
3799 // It also tracks the used pointer id bits.
3800 BitSet32 matchedLastBits(0);
3801 BitSet32 matchedCurrentBits(0);
3802 BitSet32 usedIdBits(0);
3803 bool first = true;
3804 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3805 while (heapSize > 0) {
3806 if (first) {
3807 // The first time through the loop, we just consume the root element of
3808 // the heap (the one with smallest distance).
3809 first = false;
3810 } else {
3811 // Previous iterations consumed the root element of the heap.
3812 // Pop root element off of the heap (sift down).
3813 heap[0] = heap[heapSize];
3814 for (uint32_t parentIndex = 0;;) {
3815 uint32_t childIndex = parentIndex * 2 + 1;
3816 if (childIndex >= heapSize) {
3817 break;
3818 }
3819
3820 if (childIndex + 1 < heapSize &&
3821 heap[childIndex + 1].distance < heap[childIndex].distance) {
3822 childIndex += 1;
3823 }
3824
3825 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3826 break;
3827 }
3828
3829 swap(heap[parentIndex], heap[childIndex]);
3830 parentIndex = childIndex;
3831 }
3832
3833#if DEBUG_POINTER_ASSIGNMENT
3834 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003835 for (size_t j = 0; j < heapSize; j++) {
3836 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3837 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003838 }
3839#endif
3840 }
3841
3842 heapSize -= 1;
3843
3844 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3845 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3846
3847 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3848 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3849
3850 matchedCurrentBits.markBit(currentPointerIndex);
3851 matchedLastBits.markBit(lastPointerIndex);
3852
3853 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3854 current->rawPointerData.pointers[currentPointerIndex].id = id;
3855 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3856 current->rawPointerData.markIdBit(id,
3857 current->rawPointerData.isHovering(
3858 currentPointerIndex));
3859 usedIdBits.markBit(id);
3860
3861#if DEBUG_POINTER_ASSIGNMENT
3862 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3863 ", distance=%" PRIu64,
3864 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3865#endif
3866 break;
3867 }
3868 }
3869
3870 // Assign fresh ids to pointers that were not matched in the process.
3871 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3872 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3873 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3874
3875 current->rawPointerData.pointers[currentPointerIndex].id = id;
3876 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3877 current->rawPointerData.markIdBit(id,
3878 current->rawPointerData.isHovering(currentPointerIndex));
3879
3880#if DEBUG_POINTER_ASSIGNMENT
3881 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3882#endif
3883 }
3884}
3885
3886int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3887 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3888 return AKEY_STATE_VIRTUAL;
3889 }
3890
3891 for (const VirtualKey& virtualKey : mVirtualKeys) {
3892 if (virtualKey.keyCode == keyCode) {
3893 return AKEY_STATE_UP;
3894 }
3895 }
3896
3897 return AKEY_STATE_UNKNOWN;
3898}
3899
3900int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3901 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3902 return AKEY_STATE_VIRTUAL;
3903 }
3904
3905 for (const VirtualKey& virtualKey : mVirtualKeys) {
3906 if (virtualKey.scanCode == scanCode) {
3907 return AKEY_STATE_UP;
3908 }
3909 }
3910
3911 return AKEY_STATE_UNKNOWN;
3912}
3913
3914bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3915 const int32_t* keyCodes, uint8_t* outFlags) {
3916 for (const VirtualKey& virtualKey : mVirtualKeys) {
3917 for (size_t i = 0; i < numCodes; i++) {
3918 if (virtualKey.keyCode == keyCodes[i]) {
3919 outFlags[i] = 1;
3920 }
3921 }
3922 }
3923
3924 return true;
3925}
3926
3927std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3928 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003929 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003930 return std::make_optional(mPointerController->getDisplayId());
3931 } else {
3932 return std::make_optional(mViewport.displayId);
3933 }
3934 }
3935 return std::nullopt;
3936}
3937
3938} // namespace android