blob: a9f024733f694c74656e6485a7e8ebf7452a085f [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
chaviw3277faf2021-05-19 16:45:23 -050021#include <ftl/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 Vishniakouf2f073b2021-02-09 21:59:56 +0000400 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
401 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 }
403}
404
405void TouchInputMapper::resolveExternalStylusPresence() {
406 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800407 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700408 mExternalStylusConnected = !devices.empty();
409
410 if (!mExternalStylusConnected) {
411 resetExternalStylus();
412 }
413}
414
415void TouchInputMapper::configureParameters() {
416 // Use the pointer presentation mode for devices that do not support distinct
417 // multitouch. The spot-based presentation relies on being able to accurately
418 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100420 ? Parameters::GestureMode::SINGLE_TOUCH
421 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422
423 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800424 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
425 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100427 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100429 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700430 } else if (gestureModeString != "default") {
431 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
432 }
433 }
434
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800435 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100437 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800438 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800441 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
442 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 // The device is a cursor device with a touch pad attached.
444 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100445 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446 } else {
447 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100448 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449 }
450
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800451 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452
453 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
455 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100461 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100463 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700464 } else if (deviceTypeString != "default") {
465 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
466 }
467 }
468
Michael Wright227c5542020-07-02 18:30:52 +0100469 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800470 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
471 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472
473 mParameters.hasAssociatedDisplay = false;
474 mParameters.associatedDisplayIsExternal = false;
475 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100476 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
477 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700478 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100479 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800480 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800482 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
483 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
485 }
486 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800487 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488 mParameters.hasAssociatedDisplay = true;
489 }
490
491 // Initial downs on external touch devices should wake the device.
492 // Normally we don't do this for internal touch screens to prevent them from waking
493 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 mParameters.wake = getDeviceContext().isExternal();
495 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496}
497
498void TouchInputMapper::dumpParameters(std::string& dump) {
499 dump += INDENT3 "Parameters:\n";
500
Chris Yea03dd232020-09-08 19:21:09 -0700501 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502
Chris Yea03dd232020-09-08 19:21:09 -0700503 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700504
505 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
506 "displayId='%s'\n",
507 toString(mParameters.hasAssociatedDisplay),
508 toString(mParameters.associatedDisplayIsExternal),
509 mParameters.uniqueDisplayId.c_str());
510 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
511}
512
513void TouchInputMapper::configureRawPointerAxes() {
514 mRawPointerAxes.clear();
515}
516
517void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
518 dump += INDENT3 "Raw Touch Axes:\n";
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
531 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
532}
533
534bool TouchInputMapper::hasExternalStylus() const {
535 return mExternalStylusConnected;
536}
537
538/**
539 * Determine which DisplayViewport to use.
540 * 1. If display port is specified, return the matching viewport. If matching viewport not
541 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800542 * 2. Always use the suggested viewport from WindowManagerService for pointers.
543 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700544 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800545 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700546 */
547std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800548 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800549 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700550 if (displayPort) {
551 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800552 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700553 }
554
Michael Wright227c5542020-07-02 18:30:52 +0100555 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800556 std::optional<DisplayViewport> viewport =
557 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
558 if (viewport) {
559 return viewport;
560 } else {
561 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
562 mConfig.defaultPointerDisplayId);
563 }
564 }
565
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 // Check if uniqueDisplayId is specified in idc file.
567 if (!mParameters.uniqueDisplayId.empty()) {
568 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
569 }
570
571 ViewportType viewportTypeToUse;
572 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100573 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700574 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100575 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700576 }
577
578 std::optional<DisplayViewport> viewport =
579 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100580 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700581 ALOGW("Input device %s should be associated with external display, "
582 "fallback to internal one for the external viewport is not found.",
583 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100584 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700585 }
586
587 return viewport;
588 }
589
590 // No associated display, return a non-display viewport.
591 DisplayViewport newViewport;
592 // Raw width and height in the natural orientation.
593 int32_t rawWidth = mRawPointerAxes.getRawWidth();
594 int32_t rawHeight = mRawPointerAxes.getRawHeight();
595 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
596 return std::make_optional(newViewport);
597}
598
599void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100600 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700601
602 resolveExternalStylusPresence();
603
604 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100605 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800606 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700607 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100608 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700609 if (hasStylus()) {
610 mSource |= AINPUT_SOURCE_STYLUS;
611 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800612 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700613 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;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700661 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700662 if (viewportChanged) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700663 bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700664 mViewport = *newViewport;
665
Michael Wright227c5542020-07-02 18:30:52 +0100666 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700667 // Convert rotated viewport to natural surface coordinates.
668 int32_t naturalLogicalWidth, naturalLogicalHeight;
669 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
670 int32_t naturalPhysicalLeft, naturalPhysicalTop;
671 int32_t naturalDeviceWidth, naturalDeviceHeight;
672 switch (mViewport.orientation) {
673 case DISPLAY_ORIENTATION_90:
674 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
675 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
676 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
677 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800678 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700679 naturalPhysicalTop = mViewport.physicalLeft;
680 naturalDeviceWidth = mViewport.deviceHeight;
681 naturalDeviceHeight = mViewport.deviceWidth;
682 break;
683 case DISPLAY_ORIENTATION_180:
684 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
685 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
686 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
687 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
688 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
689 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
690 naturalDeviceWidth = mViewport.deviceWidth;
691 naturalDeviceHeight = mViewport.deviceHeight;
692 break;
693 case DISPLAY_ORIENTATION_270:
694 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
695 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
696 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
697 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
698 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800699 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700700 naturalDeviceWidth = mViewport.deviceHeight;
701 naturalDeviceHeight = mViewport.deviceWidth;
702 break;
703 case DISPLAY_ORIENTATION_0:
704 default:
705 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
706 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
707 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
708 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
709 naturalPhysicalLeft = mViewport.physicalLeft;
710 naturalPhysicalTop = mViewport.physicalTop;
711 naturalDeviceWidth = mViewport.deviceWidth;
712 naturalDeviceHeight = mViewport.deviceHeight;
713 break;
714 }
715
716 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
717 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
718 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
719 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
720 }
721
722 mPhysicalWidth = naturalPhysicalWidth;
723 mPhysicalHeight = naturalPhysicalHeight;
724 mPhysicalLeft = naturalPhysicalLeft;
725 mPhysicalTop = naturalPhysicalTop;
726
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700727 const int32_t oldSurfaceWidth = mRawSurfaceWidth;
728 const int32_t oldSurfaceHeight = mRawSurfaceHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800729 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
730 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700731 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
732 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800733 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
734 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700735
Prabir Pradhand7482e72021-03-09 13:54:55 -0800736 if (isPerWindowInputRotationEnabled()) {
737 // When per-window input rotation is enabled, InputReader works in the un-rotated
738 // coordinate space, so we don't need to do anything if the device is already
739 // orientation-aware. If the device is not orientation-aware, then we need to apply
740 // the inverse rotation of the display so that when the display rotation is applied
741 // later as a part of the per-window transform, we get the expected screen
742 // coordinates.
743 mSurfaceOrientation = mParameters.orientationAware
744 ? DISPLAY_ORIENTATION_0
745 : getInverseRotation(mViewport.orientation);
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700746 // For orientation-aware devices that work in the un-rotated coordinate space, the
747 // viewport update should be skipped if it is only a change in the orientation.
748 skipViewportUpdate = mParameters.orientationAware &&
749 mRawSurfaceWidth == oldSurfaceWidth &&
750 mRawSurfaceHeight == oldSurfaceHeight && viewportOrientationChanged;
Prabir Pradhand7482e72021-03-09 13:54:55 -0800751 } else {
752 mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation
753 : DISPLAY_ORIENTATION_0;
754 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700755 } else {
756 mPhysicalWidth = rawWidth;
757 mPhysicalHeight = rawHeight;
758 mPhysicalLeft = 0;
759 mPhysicalTop = 0;
760
Arthur Hung4197f6b2020-03-16 15:39:59 +0800761 mRawSurfaceWidth = rawWidth;
762 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700763 mSurfaceLeft = 0;
764 mSurfaceTop = 0;
765 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
766 }
767 }
768
769 // If moving between pointer modes, need to reset some state.
770 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
771 if (deviceModeChanged) {
772 mOrientedRanges.clear();
773 }
774
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800775 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
776 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100777 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800778 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
779 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800780 if (mPointerController == nullptr) {
781 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700782 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800783 if (mConfig.pointerCapture) {
784 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
785 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700786 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100787 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700788 }
789
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700790 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700791 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
792 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800793 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700794 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
795
796 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800797 mXScale = float(mRawSurfaceWidth) / rawWidth;
798 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700799 mXTranslate = -mSurfaceLeft;
800 mYTranslate = -mSurfaceTop;
801 mXPrecision = 1.0f / mXScale;
802 mYPrecision = 1.0f / mYScale;
803
804 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
805 mOrientedRanges.x.source = mSource;
806 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
807 mOrientedRanges.y.source = mSource;
808
809 configureVirtualKeys();
810
811 // Scale factor for terms that are not oriented in a particular axis.
812 // If the pixels are square then xScale == yScale otherwise we fake it
813 // by choosing an average.
814 mGeometricScale = avg(mXScale, mYScale);
815
816 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800817 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700818
819 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100820 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700821 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
822 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
823 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
824 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
825 } else {
826 mSizeScale = 0.0f;
827 }
828
829 mOrientedRanges.haveTouchSize = true;
830 mOrientedRanges.haveToolSize = true;
831 mOrientedRanges.haveSize = true;
832
833 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
834 mOrientedRanges.touchMajor.source = mSource;
835 mOrientedRanges.touchMajor.min = 0;
836 mOrientedRanges.touchMajor.max = diagonalSize;
837 mOrientedRanges.touchMajor.flat = 0;
838 mOrientedRanges.touchMajor.fuzz = 0;
839 mOrientedRanges.touchMajor.resolution = 0;
840
841 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
842 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
843
844 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
845 mOrientedRanges.toolMajor.source = mSource;
846 mOrientedRanges.toolMajor.min = 0;
847 mOrientedRanges.toolMajor.max = diagonalSize;
848 mOrientedRanges.toolMajor.flat = 0;
849 mOrientedRanges.toolMajor.fuzz = 0;
850 mOrientedRanges.toolMajor.resolution = 0;
851
852 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
853 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
854
855 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
856 mOrientedRanges.size.source = mSource;
857 mOrientedRanges.size.min = 0;
858 mOrientedRanges.size.max = 1.0;
859 mOrientedRanges.size.flat = 0;
860 mOrientedRanges.size.fuzz = 0;
861 mOrientedRanges.size.resolution = 0;
862 } else {
863 mSizeScale = 0.0f;
864 }
865
866 // Pressure factors.
867 mPressureScale = 0;
868 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100869 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
870 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700871 if (mCalibration.havePressureScale) {
872 mPressureScale = mCalibration.pressureScale;
873 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
874 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
875 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
876 }
877 }
878
879 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
880 mOrientedRanges.pressure.source = mSource;
881 mOrientedRanges.pressure.min = 0;
882 mOrientedRanges.pressure.max = pressureMax;
883 mOrientedRanges.pressure.flat = 0;
884 mOrientedRanges.pressure.fuzz = 0;
885 mOrientedRanges.pressure.resolution = 0;
886
887 // Tilt
888 mTiltXCenter = 0;
889 mTiltXScale = 0;
890 mTiltYCenter = 0;
891 mTiltYScale = 0;
892 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
893 if (mHaveTilt) {
894 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
895 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
896 mTiltXScale = M_PI / 180;
897 mTiltYScale = M_PI / 180;
898
Tatsunosuke Tobita35e05532021-06-30 14:49:32 +0900899 if (mRawPointerAxes.tiltX.resolution) {
900 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
901 }
902 if (mRawPointerAxes.tiltY.resolution) {
903 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
904 }
905
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700906 mOrientedRanges.haveTilt = true;
907
908 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
909 mOrientedRanges.tilt.source = mSource;
910 mOrientedRanges.tilt.min = 0;
911 mOrientedRanges.tilt.max = M_PI_2;
912 mOrientedRanges.tilt.flat = 0;
913 mOrientedRanges.tilt.fuzz = 0;
914 mOrientedRanges.tilt.resolution = 0;
915 }
916
917 // Orientation
918 mOrientationScale = 0;
919 if (mHaveTilt) {
920 mOrientedRanges.haveOrientation = true;
921
922 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
923 mOrientedRanges.orientation.source = mSource;
924 mOrientedRanges.orientation.min = -M_PI;
925 mOrientedRanges.orientation.max = M_PI;
926 mOrientedRanges.orientation.flat = 0;
927 mOrientedRanges.orientation.fuzz = 0;
928 mOrientedRanges.orientation.resolution = 0;
929 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100930 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100932 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700933 if (mRawPointerAxes.orientation.valid) {
934 if (mRawPointerAxes.orientation.maxValue > 0) {
935 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
936 } else if (mRawPointerAxes.orientation.minValue < 0) {
937 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
938 } else {
939 mOrientationScale = 0;
940 }
941 }
942 }
943
944 mOrientedRanges.haveOrientation = true;
945
946 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
947 mOrientedRanges.orientation.source = mSource;
948 mOrientedRanges.orientation.min = -M_PI_2;
949 mOrientedRanges.orientation.max = M_PI_2;
950 mOrientedRanges.orientation.flat = 0;
951 mOrientedRanges.orientation.fuzz = 0;
952 mOrientedRanges.orientation.resolution = 0;
953 }
954
955 // Distance
956 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100957 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
958 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700959 if (mCalibration.haveDistanceScale) {
960 mDistanceScale = mCalibration.distanceScale;
961 } else {
962 mDistanceScale = 1.0f;
963 }
964 }
965
966 mOrientedRanges.haveDistance = true;
967
968 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
969 mOrientedRanges.distance.source = mSource;
970 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
971 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
972 mOrientedRanges.distance.flat = 0;
973 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
974 mOrientedRanges.distance.resolution = 0;
975 }
976
977 // Compute oriented precision, scales and ranges.
978 // Note that the maximum value reported is an inclusive maximum value so it is one
979 // unit less than the total width or height of surface.
980 switch (mSurfaceOrientation) {
981 case DISPLAY_ORIENTATION_90:
982 case DISPLAY_ORIENTATION_270:
983 mOrientedXPrecision = mYPrecision;
984 mOrientedYPrecision = mXPrecision;
985
986 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800987 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700988 mOrientedRanges.x.flat = 0;
989 mOrientedRanges.x.fuzz = 0;
990 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
991
992 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800993 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994 mOrientedRanges.y.flat = 0;
995 mOrientedRanges.y.fuzz = 0;
996 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
997 break;
998
999 default:
1000 mOrientedXPrecision = mXPrecision;
1001 mOrientedYPrecision = mYPrecision;
1002
1003 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001004 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001005 mOrientedRanges.x.flat = 0;
1006 mOrientedRanges.x.fuzz = 0;
1007 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1008
1009 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001010 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011 mOrientedRanges.y.flat = 0;
1012 mOrientedRanges.y.fuzz = 0;
1013 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1014 break;
1015 }
1016
1017 // Location
1018 updateAffineTransformation();
1019
Michael Wright227c5542020-07-02 18:30:52 +01001020 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001021 // Compute pointer gesture detection parameters.
1022 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001023 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001024
1025 // Scale movements such that one whole swipe of the touch pad covers a
1026 // given area relative to the diagonal size of the display when no acceleration
1027 // is applied.
1028 // Assume that the touch pad has a square aspect ratio such that movements in
1029 // X and Y of the same number of raw units cover the same physical distance.
1030 mPointerXMovementScale =
1031 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1032 mPointerYMovementScale = mPointerXMovementScale;
1033
1034 // Scale zooms to cover a smaller range of the display than movements do.
1035 // This value determines the area around the pointer that is affected by freeform
1036 // pointer gestures.
1037 mPointerXZoomScale =
1038 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1039 mPointerYZoomScale = mPointerXZoomScale;
1040
1041 // Max width between pointers to detect a swipe gesture is more than some fraction
1042 // of the diagonal axis of the touch pad. Touches that are wider than this are
1043 // translated into freeform gestures.
1044 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1045
1046 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001047 const nsecs_t readTime = when; // synthetic event
1048 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001049 }
1050
1051 // Inform the dispatcher about the changes.
1052 *outResetNeeded = true;
1053 bumpGeneration();
1054 }
1055}
1056
1057void TouchInputMapper::dumpSurface(std::string& dump) {
1058 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001059 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1060 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001061 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1062 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001063 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1064 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001065 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1066 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1067 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1068 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1069 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1070}
1071
1072void TouchInputMapper::configureVirtualKeys() {
1073 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001074 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001075
1076 mVirtualKeys.clear();
1077
1078 if (virtualKeyDefinitions.size() == 0) {
1079 return;
1080 }
1081
1082 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1083 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1084 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1085 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1086
1087 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1088 VirtualKey virtualKey;
1089
1090 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1091 int32_t keyCode;
1092 int32_t dummyKeyMetaState;
1093 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001094 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1095 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001096 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1097 continue; // drop the key
1098 }
1099
1100 virtualKey.keyCode = keyCode;
1101 virtualKey.flags = flags;
1102
1103 // convert the key definition's display coordinates into touch coordinates for a hit box
1104 int32_t halfWidth = virtualKeyDefinition.width / 2;
1105 int32_t halfHeight = virtualKeyDefinition.height / 2;
1106
1107 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001108 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 touchScreenLeft;
1110 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001111 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001113 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1114 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001115 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001116 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1117 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001118 touchScreenTop;
1119 mVirtualKeys.push_back(virtualKey);
1120 }
1121}
1122
1123void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1124 if (!mVirtualKeys.empty()) {
1125 dump += INDENT3 "Virtual Keys:\n";
1126
1127 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1128 const VirtualKey& virtualKey = mVirtualKeys[i];
1129 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1130 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1131 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1132 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1133 }
1134 }
1135}
1136
1137void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001138 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 Calibration& out = mCalibration;
1140
1141 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 String8 sizeCalibrationString;
1144 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1145 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001148 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001150 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001152 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001153 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001154 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 } else if (sizeCalibrationString != "default") {
1156 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1157 }
1158 }
1159
1160 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1161 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1162 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1163
1164 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001165 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 String8 pressureCalibrationString;
1167 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1168 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (pressureCalibrationString != "default") {
1175 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1176 pressureCalibrationString.string());
1177 }
1178 }
1179
1180 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1181
1182 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 String8 orientationCalibrationString;
1185 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1186 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 } else if (orientationCalibrationString != "default") {
1193 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1194 orientationCalibrationString.string());
1195 }
1196 }
1197
1198 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 String8 distanceCalibrationString;
1201 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1202 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001203 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001206 } else if (distanceCalibrationString != "default") {
1207 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1208 distanceCalibrationString.string());
1209 }
1210 }
1211
1212 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1213
Michael Wright227c5542020-07-02 18:30:52 +01001214 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 String8 coverageCalibrationString;
1216 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1217 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001220 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 } else if (coverageCalibrationString != "default") {
1222 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1223 coverageCalibrationString.string());
1224 }
1225 }
1226}
1227
1228void TouchInputMapper::resolveCalibration() {
1229 // Size
1230 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001231 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1232 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 }
1234 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001235 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 }
1237
1238 // Pressure
1239 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001240 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1241 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 }
1243 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001244 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 }
1246
1247 // Orientation
1248 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001249 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1250 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 }
1252 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001253 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 }
1255
1256 // Distance
1257 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001258 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1259 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 }
1261 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001262 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 }
1264
1265 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001266 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1267 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 }
1269}
1270
1271void TouchInputMapper::dumpCalibration(std::string& dump) {
1272 dump += INDENT3 "Calibration:\n";
1273
1274 // Size
1275 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001276 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 dump += INDENT4 "touch.size.calibration: none\n";
1278 break;
Michael Wright227c5542020-07-02 18:30:52 +01001279 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 dump += INDENT4 "touch.size.calibration: geometric\n";
1281 break;
Michael Wright227c5542020-07-02 18:30:52 +01001282 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 dump += INDENT4 "touch.size.calibration: diameter\n";
1284 break;
Michael Wright227c5542020-07-02 18:30:52 +01001285 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286 dump += INDENT4 "touch.size.calibration: box\n";
1287 break;
Michael Wright227c5542020-07-02 18:30:52 +01001288 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 dump += INDENT4 "touch.size.calibration: area\n";
1290 break;
1291 default:
1292 ALOG_ASSERT(false);
1293 }
1294
1295 if (mCalibration.haveSizeScale) {
1296 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1297 }
1298
1299 if (mCalibration.haveSizeBias) {
1300 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1301 }
1302
1303 if (mCalibration.haveSizeIsSummed) {
1304 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1305 toString(mCalibration.sizeIsSummed));
1306 }
1307
1308 // Pressure
1309 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001310 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 dump += INDENT4 "touch.pressure.calibration: none\n";
1312 break;
Michael Wright227c5542020-07-02 18:30:52 +01001313 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314 dump += INDENT4 "touch.pressure.calibration: physical\n";
1315 break;
Michael Wright227c5542020-07-02 18:30:52 +01001316 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1318 break;
1319 default:
1320 ALOG_ASSERT(false);
1321 }
1322
1323 if (mCalibration.havePressureScale) {
1324 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1325 }
1326
1327 // Orientation
1328 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.orientation.calibration: none\n";
1331 break;
Michael Wright227c5542020-07-02 18:30:52 +01001332 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1334 break;
Michael Wright227c5542020-07-02 18:30:52 +01001335 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001336 dump += INDENT4 "touch.orientation.calibration: vector\n";
1337 break;
1338 default:
1339 ALOG_ASSERT(false);
1340 }
1341
1342 // Distance
1343 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001344 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001345 dump += INDENT4 "touch.distance.calibration: none\n";
1346 break;
Michael Wright227c5542020-07-02 18:30:52 +01001347 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001348 dump += INDENT4 "touch.distance.calibration: scaled\n";
1349 break;
1350 default:
1351 ALOG_ASSERT(false);
1352 }
1353
1354 if (mCalibration.haveDistanceScale) {
1355 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1356 }
1357
1358 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001359 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360 dump += INDENT4 "touch.coverage.calibration: none\n";
1361 break;
Michael Wright227c5542020-07-02 18:30:52 +01001362 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001363 dump += INDENT4 "touch.coverage.calibration: box\n";
1364 break;
1365 default:
1366 ALOG_ASSERT(false);
1367 }
1368}
1369
1370void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1371 dump += INDENT3 "Affine Transformation:\n";
1372
1373 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1374 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1375 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1376 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1377 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1378 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1379}
1380
1381void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001382 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001383 mSurfaceOrientation);
1384}
1385
1386void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001387 mCursorButtonAccumulator.reset(getDeviceContext());
1388 mCursorScrollAccumulator.reset(getDeviceContext());
1389 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001390
1391 mPointerVelocityControl.reset();
1392 mWheelXVelocityControl.reset();
1393 mWheelYVelocityControl.reset();
1394
1395 mRawStatesPending.clear();
1396 mCurrentRawState.clear();
1397 mCurrentCookedState.clear();
1398 mLastRawState.clear();
1399 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001400 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001401 mSentHoverEnter = false;
1402 mHavePointerIds = false;
1403 mCurrentMotionAborted = false;
1404 mDownTime = 0;
1405
1406 mCurrentVirtualKey.down = false;
1407
1408 mPointerGesture.reset();
1409 mPointerSimple.reset();
1410 resetExternalStylus();
1411
1412 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001413 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001414 mPointerController->clearSpots();
1415 }
1416
1417 InputMapper::reset(when);
1418}
1419
1420void TouchInputMapper::resetExternalStylus() {
1421 mExternalStylusState.clear();
1422 mExternalStylusId = -1;
1423 mExternalStylusFusionTimeout = LLONG_MAX;
1424 mExternalStylusDataPending = false;
1425}
1426
1427void TouchInputMapper::clearStylusDataPendingFlags() {
1428 mExternalStylusDataPending = false;
1429 mExternalStylusFusionTimeout = LLONG_MAX;
1430}
1431
1432void TouchInputMapper::process(const RawEvent* rawEvent) {
1433 mCursorButtonAccumulator.process(rawEvent);
1434 mCursorScrollAccumulator.process(rawEvent);
1435 mTouchButtonAccumulator.process(rawEvent);
1436
1437 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001438 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439 }
1440}
1441
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001442void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001443 // Push a new state.
1444 mRawStatesPending.emplace_back();
1445
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001446 RawState& next = mRawStatesPending.back();
1447 next.clear();
1448 next.when = when;
1449 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001450
1451 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001452 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001453 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1454
1455 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001456 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1457 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001458 mCursorScrollAccumulator.finishSync();
1459
1460 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001461 syncTouch(when, &next);
1462
1463 // The last RawState is the actually second to last, since we just added a new state
1464 const RawState& last =
1465 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001466
1467 // Assign pointer ids.
1468 if (!mHavePointerIds) {
1469 assignPointerIds(last, next);
1470 }
1471
1472#if DEBUG_RAW_EVENTS
1473 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001474 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001475 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1476 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1477 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1478 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479#endif
1480
Arthur Hung9ad18942021-06-19 02:04:46 +00001481 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1482 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1483 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1484 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1485 next.rawPointerData.hoveringIdBits.value);
1486 }
1487
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001488 processRawTouches(false /*timeout*/);
1489}
1490
1491void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001492 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001493 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001494 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001495 mCurrentCookedState.clear();
1496 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001497 return;
1498 }
1499
1500 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1501 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1502 // touching the current state will only observe the events that have been dispatched to the
1503 // rest of the pipeline.
1504 const size_t N = mRawStatesPending.size();
1505 size_t count;
1506 for (count = 0; count < N; count++) {
1507 const RawState& next = mRawStatesPending[count];
1508
1509 // A failure to assign the stylus id means that we're waiting on stylus data
1510 // and so should defer the rest of the pipeline.
1511 if (assignExternalStylusId(next, timeout)) {
1512 break;
1513 }
1514
1515 // All ready to go.
1516 clearStylusDataPendingFlags();
1517 mCurrentRawState.copyFrom(next);
1518 if (mCurrentRawState.when < mLastRawState.when) {
1519 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001520 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001522 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001523 }
1524 if (count != 0) {
1525 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1526 }
1527
1528 if (mExternalStylusDataPending) {
1529 if (timeout) {
1530 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1531 clearStylusDataPendingFlags();
1532 mCurrentRawState.copyFrom(mLastRawState);
1533#if DEBUG_STYLUS_FUSION
1534 ALOGD("Timeout expired, synthesizing event with new stylus data");
1535#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001536 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1537 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001538 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1539 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1540 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1541 }
1542 }
1543}
1544
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001545void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001546 // Always start with a clean state.
1547 mCurrentCookedState.clear();
1548
1549 // Apply stylus buttons to current raw state.
1550 applyExternalStylusButtonState(when);
1551
1552 // Handle policy on initial down or hover events.
1553 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1554 mCurrentRawState.rawPointerData.pointerCount != 0;
1555
1556 uint32_t policyFlags = 0;
1557 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1558 if (initialDown || buttonsPressed) {
1559 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001560 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001561 getContext()->fadePointer();
1562 }
1563
1564 if (mParameters.wake) {
1565 policyFlags |= POLICY_FLAG_WAKE;
1566 }
1567 }
1568
1569 // Consume raw off-screen touches before cooking pointer data.
1570 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001571 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001572 mCurrentRawState.rawPointerData.clear();
1573 }
1574
1575 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1576 // with cooked pointer data that has the same ids and indices as the raw data.
1577 // The following code can use either the raw or cooked data, as needed.
1578 cookPointerData();
1579
1580 // Apply stylus pressure to current cooked state.
1581 applyExternalStylusTouchState(when);
1582
1583 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001584 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1585 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001586 mCurrentCookedState.buttonState);
1587
1588 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001589 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1591 uint32_t id = idBits.clearFirstMarkedBit();
1592 const RawPointerData::Pointer& pointer =
1593 mCurrentRawState.rawPointerData.pointerForId(id);
1594 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1595 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1596 mCurrentCookedState.stylusIdBits.markBit(id);
1597 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1598 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1599 mCurrentCookedState.fingerIdBits.markBit(id);
1600 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1601 mCurrentCookedState.mouseIdBits.markBit(id);
1602 }
1603 }
1604 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1605 uint32_t id = idBits.clearFirstMarkedBit();
1606 const RawPointerData::Pointer& pointer =
1607 mCurrentRawState.rawPointerData.pointerForId(id);
1608 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1609 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1610 mCurrentCookedState.stylusIdBits.markBit(id);
1611 }
1612 }
1613
1614 // Stylus takes precedence over all tools, then mouse, then finger.
1615 PointerUsage pointerUsage = mPointerUsage;
1616 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1617 mCurrentCookedState.mouseIdBits.clear();
1618 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001619 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1621 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001622 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001623 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1624 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001625 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626 }
1627
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001628 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001630 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001631
1632 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001633 dispatchButtonRelease(when, readTime, policyFlags);
1634 dispatchHoverExit(when, readTime, policyFlags);
1635 dispatchTouches(when, readTime, policyFlags);
1636 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1637 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001638 }
1639
1640 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1641 mCurrentMotionAborted = false;
1642 }
1643 }
1644
1645 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001646 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1648 mCurrentCookedState.buttonState);
1649
1650 // Clear some transient state.
1651 mCurrentRawState.rawVScroll = 0;
1652 mCurrentRawState.rawHScroll = 0;
1653
1654 // Copy current touch to last touch in preparation for the next cycle.
1655 mLastRawState.copyFrom(mCurrentRawState);
1656 mLastCookedState.copyFrom(mCurrentCookedState);
1657}
1658
Garfield Tanc734e4f2021-01-15 20:01:39 -08001659void TouchInputMapper::updateTouchSpots() {
1660 if (!mConfig.showTouches || mPointerController == nullptr) {
1661 return;
1662 }
1663
1664 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1665 // clear touch spots.
1666 if (mDeviceMode != DeviceMode::DIRECT &&
1667 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1668 return;
1669 }
1670
1671 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1672 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1673
1674 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001675 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1676 mCurrentCookedState.cookedPointerData.idToIndex,
1677 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001678}
1679
1680bool TouchInputMapper::isTouchScreen() {
1681 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1682 mParameters.hasAssociatedDisplay;
1683}
1684
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001685void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001686 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001687 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1688 }
1689}
1690
1691void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1692 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1693 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1694
1695 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1696 float pressure = mExternalStylusState.pressure;
1697 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1698 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1699 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1700 }
1701 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1702 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1703
1704 PointerProperties& properties =
1705 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1706 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1707 properties.toolType = mExternalStylusState.toolType;
1708 }
1709 }
1710}
1711
1712bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001713 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714 return false;
1715 }
1716
1717 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1718 state.rawPointerData.pointerCount != 0;
1719 if (initialDown) {
1720 if (mExternalStylusState.pressure != 0.0f) {
1721#if DEBUG_STYLUS_FUSION
1722 ALOGD("Have both stylus and touch data, beginning fusion");
1723#endif
1724 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1725 } else if (timeout) {
1726#if DEBUG_STYLUS_FUSION
1727 ALOGD("Timeout expired, assuming touch is not a stylus.");
1728#endif
1729 resetExternalStylus();
1730 } else {
1731 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1732 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1733 }
1734#if DEBUG_STYLUS_FUSION
1735 ALOGD("No stylus data but stylus is connected, requesting timeout "
1736 "(%" PRId64 "ms)",
1737 mExternalStylusFusionTimeout);
1738#endif
1739 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1740 return true;
1741 }
1742 }
1743
1744 // Check if the stylus pointer has gone up.
1745 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1746#if DEBUG_STYLUS_FUSION
1747 ALOGD("Stylus pointer is going up");
1748#endif
1749 mExternalStylusId = -1;
1750 }
1751
1752 return false;
1753}
1754
1755void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001756 if (mDeviceMode == DeviceMode::POINTER) {
1757 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001758 // Since this is a synthetic event, we can consider its latency to be zero
1759 const nsecs_t readTime = when;
1760 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001761 }
Michael Wright227c5542020-07-02 18:30:52 +01001762 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001763 if (mExternalStylusFusionTimeout < when) {
1764 processRawTouches(true /*timeout*/);
1765 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1766 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1767 }
1768 }
1769}
1770
1771void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1772 mExternalStylusState.copyFrom(state);
1773 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1774 // We're either in the middle of a fused stream of data or we're waiting on data before
1775 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1776 // data.
1777 mExternalStylusDataPending = true;
1778 processRawTouches(false /*timeout*/);
1779 }
1780}
1781
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001782bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001783 // Check for release of a virtual key.
1784 if (mCurrentVirtualKey.down) {
1785 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1786 // Pointer went up while virtual key was down.
1787 mCurrentVirtualKey.down = false;
1788 if (!mCurrentVirtualKey.ignored) {
1789#if DEBUG_VIRTUAL_KEYS
1790 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1791 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1792#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001793 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001794 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1795 }
1796 return true;
1797 }
1798
1799 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1800 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1801 const RawPointerData::Pointer& pointer =
1802 mCurrentRawState.rawPointerData.pointerForId(id);
1803 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1804 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1805 // Pointer is still within the space of the virtual key.
1806 return true;
1807 }
1808 }
1809
1810 // Pointer left virtual key area or another pointer also went down.
1811 // Send key cancellation but do not consume the touch yet.
1812 // This is useful when the user swipes through from the virtual key area
1813 // into the main display surface.
1814 mCurrentVirtualKey.down = false;
1815 if (!mCurrentVirtualKey.ignored) {
1816#if DEBUG_VIRTUAL_KEYS
1817 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1818 mCurrentVirtualKey.scanCode);
1819#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001820 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001821 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1822 AKEY_EVENT_FLAG_CANCELED);
1823 }
1824 }
1825
1826 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1827 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1828 // Pointer just went down. Check for virtual key press or off-screen touches.
1829 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1830 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001831 // Exclude unscaled device for inside surface checking.
1832 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001833 // If exactly one pointer went down, check for virtual key hit.
1834 // Otherwise we will drop the entire stroke.
1835 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1836 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1837 if (virtualKey) {
1838 mCurrentVirtualKey.down = true;
1839 mCurrentVirtualKey.downTime = when;
1840 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1841 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1842 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001843 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1844 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001845
1846 if (!mCurrentVirtualKey.ignored) {
1847#if DEBUG_VIRTUAL_KEYS
1848 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1849 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1850#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001851 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001852 AKEY_EVENT_FLAG_FROM_SYSTEM |
1853 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1854 }
1855 }
1856 }
1857 return true;
1858 }
1859 }
1860
1861 // Disable all virtual key touches that happen within a short time interval of the
1862 // most recent touch within the screen area. The idea is to filter out stray
1863 // virtual key presses when interacting with the touch screen.
1864 //
1865 // Problems we're trying to solve:
1866 //
1867 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1868 // virtual key area that is implemented by a separate touch panel and accidentally
1869 // triggers a virtual key.
1870 //
1871 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1872 // area and accidentally triggers a virtual key. This often happens when virtual keys
1873 // are layed out below the screen near to where the on screen keyboard's space bar
1874 // is displayed.
1875 if (mConfig.virtualKeyQuietTime > 0 &&
1876 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001877 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001878 }
1879 return false;
1880}
1881
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001882void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001883 int32_t keyEventAction, int32_t keyEventFlags) {
1884 int32_t keyCode = mCurrentVirtualKey.keyCode;
1885 int32_t scanCode = mCurrentVirtualKey.scanCode;
1886 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001887 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001888 policyFlags |= POLICY_FLAG_VIRTUAL;
1889
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001890 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1891 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1892 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001893 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001894}
1895
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001896void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001897 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1898 if (!currentIdBits.isEmpty()) {
1899 int32_t metaState = getContext()->getGlobalMetaState();
1900 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001901 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1902 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001903 mCurrentCookedState.cookedPointerData.pointerProperties,
1904 mCurrentCookedState.cookedPointerData.pointerCoords,
1905 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1906 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1907 mCurrentMotionAborted = true;
1908 }
1909}
1910
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001911void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001912 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1913 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1914 int32_t metaState = getContext()->getGlobalMetaState();
1915 int32_t buttonState = mCurrentCookedState.buttonState;
1916
1917 if (currentIdBits == lastIdBits) {
1918 if (!currentIdBits.isEmpty()) {
1919 // No pointer id changes so this is a move event.
1920 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001921 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1922 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001923 mCurrentCookedState.cookedPointerData.pointerProperties,
1924 mCurrentCookedState.cookedPointerData.pointerCoords,
1925 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1926 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1927 }
1928 } else {
1929 // There may be pointers going up and pointers going down and pointers moving
1930 // all at the same time.
1931 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1932 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1933 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1934 BitSet32 dispatchedIdBits(lastIdBits.value);
1935
1936 // Update last coordinates of pointers that have moved so that we observe the new
1937 // pointer positions at the same time as other pointers that have just gone up.
1938 bool moveNeeded =
1939 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1940 mCurrentCookedState.cookedPointerData.pointerCoords,
1941 mCurrentCookedState.cookedPointerData.idToIndex,
1942 mLastCookedState.cookedPointerData.pointerProperties,
1943 mLastCookedState.cookedPointerData.pointerCoords,
1944 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1945 if (buttonState != mLastCookedState.buttonState) {
1946 moveNeeded = true;
1947 }
1948
1949 // Dispatch pointer up events.
1950 while (!upIdBits.isEmpty()) {
1951 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001952 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001953 if (isCanceled) {
1954 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1955 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001956 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001957 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001958 mLastCookedState.cookedPointerData.pointerProperties,
1959 mLastCookedState.cookedPointerData.pointerCoords,
1960 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1961 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1962 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001963 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001964 }
1965
1966 // Dispatch move events if any of the remaining pointers moved from their old locations.
1967 // Although applications receive new locations as part of individual pointer up
1968 // events, they do not generally handle them except when presented in a move event.
1969 if (moveNeeded && !moveIdBits.isEmpty()) {
1970 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001971 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1972 metaState, buttonState, 0,
1973 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001974 mCurrentCookedState.cookedPointerData.pointerCoords,
1975 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1976 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1977 }
1978
1979 // Dispatch pointer down events using the new pointer locations.
1980 while (!downIdBits.isEmpty()) {
1981 uint32_t downId = downIdBits.clearFirstMarkedBit();
1982 dispatchedIdBits.markBit(downId);
1983
1984 if (dispatchedIdBits.count() == 1) {
1985 // First pointer is going down. Set down time.
1986 mDownTime = when;
1987 }
1988
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001989 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
1990 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001991 mCurrentCookedState.cookedPointerData.pointerProperties,
1992 mCurrentCookedState.cookedPointerData.pointerCoords,
1993 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1994 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1995 }
1996 }
1997}
1998
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001999void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002000 if (mSentHoverEnter &&
2001 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2002 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2003 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002004 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2005 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002006 mLastCookedState.cookedPointerData.pointerProperties,
2007 mLastCookedState.cookedPointerData.pointerCoords,
2008 mLastCookedState.cookedPointerData.idToIndex,
2009 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2010 mOrientedYPrecision, mDownTime);
2011 mSentHoverEnter = false;
2012 }
2013}
2014
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002015void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2016 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002017 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2018 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2019 int32_t metaState = getContext()->getGlobalMetaState();
2020 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002021 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2022 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002023 mCurrentCookedState.cookedPointerData.pointerProperties,
2024 mCurrentCookedState.cookedPointerData.pointerCoords,
2025 mCurrentCookedState.cookedPointerData.idToIndex,
2026 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2027 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2028 mSentHoverEnter = true;
2029 }
2030
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002031 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2032 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002033 mCurrentCookedState.cookedPointerData.pointerProperties,
2034 mCurrentCookedState.cookedPointerData.pointerCoords,
2035 mCurrentCookedState.cookedPointerData.idToIndex,
2036 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2037 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2038 }
2039}
2040
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002041void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002042 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2043 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2044 const int32_t metaState = getContext()->getGlobalMetaState();
2045 int32_t buttonState = mLastCookedState.buttonState;
2046 while (!releasedButtons.isEmpty()) {
2047 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2048 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002049 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002050 actionButton, 0, metaState, buttonState, 0,
2051 mCurrentCookedState.cookedPointerData.pointerProperties,
2052 mCurrentCookedState.cookedPointerData.pointerCoords,
2053 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2054 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2055 }
2056}
2057
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002058void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002059 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2060 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2061 const int32_t metaState = getContext()->getGlobalMetaState();
2062 int32_t buttonState = mLastCookedState.buttonState;
2063 while (!pressedButtons.isEmpty()) {
2064 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2065 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002066 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2067 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002068 mCurrentCookedState.cookedPointerData.pointerProperties,
2069 mCurrentCookedState.cookedPointerData.pointerCoords,
2070 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2071 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2072 }
2073}
2074
2075const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2076 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2077 return cookedPointerData.touchingIdBits;
2078 }
2079 return cookedPointerData.hoveringIdBits;
2080}
2081
2082void TouchInputMapper::cookPointerData() {
2083 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2084
2085 mCurrentCookedState.cookedPointerData.clear();
2086 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2087 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2088 mCurrentRawState.rawPointerData.hoveringIdBits;
2089 mCurrentCookedState.cookedPointerData.touchingIdBits =
2090 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002091 mCurrentCookedState.cookedPointerData.canceledIdBits =
2092 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002093
2094 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2095 mCurrentCookedState.buttonState = 0;
2096 } else {
2097 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2098 }
2099
2100 // Walk through the the active pointers and map device coordinates onto
2101 // surface coordinates and adjust for display orientation.
2102 for (uint32_t i = 0; i < currentPointerCount; i++) {
2103 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2104
2105 // Size
2106 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2107 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002108 case Calibration::SizeCalibration::GEOMETRIC:
2109 case Calibration::SizeCalibration::DIAMETER:
2110 case Calibration::SizeCalibration::BOX:
2111 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002112 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2113 touchMajor = in.touchMajor;
2114 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2115 toolMajor = in.toolMajor;
2116 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2117 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2118 : in.touchMajor;
2119 } else if (mRawPointerAxes.touchMajor.valid) {
2120 toolMajor = touchMajor = in.touchMajor;
2121 toolMinor = touchMinor =
2122 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2123 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2124 : in.touchMajor;
2125 } else if (mRawPointerAxes.toolMajor.valid) {
2126 touchMajor = toolMajor = in.toolMajor;
2127 touchMinor = toolMinor =
2128 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2129 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2130 : in.toolMajor;
2131 } else {
2132 ALOG_ASSERT(false,
2133 "No touch or tool axes. "
2134 "Size calibration should have been resolved to NONE.");
2135 touchMajor = 0;
2136 touchMinor = 0;
2137 toolMajor = 0;
2138 toolMinor = 0;
2139 size = 0;
2140 }
2141
2142 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2143 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2144 if (touchingCount > 1) {
2145 touchMajor /= touchingCount;
2146 touchMinor /= touchingCount;
2147 toolMajor /= touchingCount;
2148 toolMinor /= touchingCount;
2149 size /= touchingCount;
2150 }
2151 }
2152
Michael Wright227c5542020-07-02 18:30:52 +01002153 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154 touchMajor *= mGeometricScale;
2155 touchMinor *= mGeometricScale;
2156 toolMajor *= mGeometricScale;
2157 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002158 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002159 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2160 touchMinor = touchMajor;
2161 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2162 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002163 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002164 touchMinor = touchMajor;
2165 toolMinor = toolMajor;
2166 }
2167
2168 mCalibration.applySizeScaleAndBias(&touchMajor);
2169 mCalibration.applySizeScaleAndBias(&touchMinor);
2170 mCalibration.applySizeScaleAndBias(&toolMajor);
2171 mCalibration.applySizeScaleAndBias(&toolMinor);
2172 size *= mSizeScale;
2173 break;
2174 default:
2175 touchMajor = 0;
2176 touchMinor = 0;
2177 toolMajor = 0;
2178 toolMinor = 0;
2179 size = 0;
2180 break;
2181 }
2182
2183 // Pressure
2184 float pressure;
2185 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002186 case Calibration::PressureCalibration::PHYSICAL:
2187 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002188 pressure = in.pressure * mPressureScale;
2189 break;
2190 default:
2191 pressure = in.isHovering ? 0 : 1;
2192 break;
2193 }
2194
2195 // Tilt and Orientation
2196 float tilt;
2197 float orientation;
2198 if (mHaveTilt) {
2199 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2200 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2201 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2202 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2203 } else {
2204 tilt = 0;
2205
2206 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002207 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002208 orientation = in.orientation * mOrientationScale;
2209 break;
Michael Wright227c5542020-07-02 18:30:52 +01002210 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002211 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2212 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2213 if (c1 != 0 || c2 != 0) {
2214 orientation = atan2f(c1, c2) * 0.5f;
2215 float confidence = hypotf(c1, c2);
2216 float scale = 1.0f + confidence / 16.0f;
2217 touchMajor *= scale;
2218 touchMinor /= scale;
2219 toolMajor *= scale;
2220 toolMinor /= scale;
2221 } else {
2222 orientation = 0;
2223 }
2224 break;
2225 }
2226 default:
2227 orientation = 0;
2228 }
2229 }
2230
2231 // Distance
2232 float distance;
2233 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002234 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002235 distance = in.distance * mDistanceScale;
2236 break;
2237 default:
2238 distance = 0;
2239 }
2240
2241 // Coverage
2242 int32_t rawLeft, rawTop, rawRight, rawBottom;
2243 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002244 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002245 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2246 rawRight = in.toolMinor & 0x0000ffff;
2247 rawBottom = in.toolMajor & 0x0000ffff;
2248 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2249 break;
2250 default:
2251 rawLeft = rawTop = rawRight = rawBottom = 0;
2252 break;
2253 }
2254
2255 // Adjust X,Y coords for device calibration
2256 // TODO: Adjust coverage coords?
2257 float xTransformed = in.x, yTransformed = in.y;
2258 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002259 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002260
2261 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002262 float left, top, right, bottom;
2263
2264 switch (mSurfaceOrientation) {
2265 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002266 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2267 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2268 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2269 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2270 orientation -= M_PI_2;
2271 if (mOrientedRanges.haveOrientation &&
2272 orientation < mOrientedRanges.orientation.min) {
2273 orientation +=
2274 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2275 }
2276 break;
2277 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002278 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2279 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2280 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2281 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2282 orientation -= M_PI;
2283 if (mOrientedRanges.haveOrientation &&
2284 orientation < mOrientedRanges.orientation.min) {
2285 orientation +=
2286 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2287 }
2288 break;
2289 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002290 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2291 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2292 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2293 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2294 orientation += M_PI_2;
2295 if (mOrientedRanges.haveOrientation &&
2296 orientation > mOrientedRanges.orientation.max) {
2297 orientation -=
2298 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2299 }
2300 break;
2301 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002302 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2303 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2304 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2305 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2306 break;
2307 }
2308
2309 // Write output coords.
2310 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2311 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002312 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2313 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002314 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2315 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2316 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2317 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2318 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2319 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2320 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002321 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002322 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2323 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2324 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2325 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2326 } else {
2327 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2328 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2329 }
2330
Chris Ye364fdb52020-08-05 15:07:56 -07002331 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002332 uint32_t id = in.id;
2333 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2334 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2335 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2336 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2337 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2338 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2339 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2340 }
2341
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002342 // Write output properties.
2343 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 properties.clear();
2345 properties.id = id;
2346 properties.toolType = in.toolType;
2347
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002348 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002350 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 }
2352}
2353
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002354void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 PointerUsage pointerUsage) {
2356 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002357 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 mPointerUsage = pointerUsage;
2359 }
2360
2361 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002362 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002363 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002364 break;
Michael Wright227c5542020-07-02 18:30:52 +01002365 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002366 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 break;
Michael Wright227c5542020-07-02 18:30:52 +01002368 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002369 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 break;
Michael Wright227c5542020-07-02 18:30:52 +01002371 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 break;
2373 }
2374}
2375
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002376void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002378 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002379 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 break;
Michael Wright227c5542020-07-02 18:30:52 +01002381 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002382 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 break;
Michael Wright227c5542020-07-02 18:30:52 +01002384 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002385 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002386 break;
Michael Wright227c5542020-07-02 18:30:52 +01002387 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 break;
2389 }
2390
Michael Wright227c5542020-07-02 18:30:52 +01002391 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392}
2393
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002394void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2395 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 // Update current gesture coordinates.
2397 bool cancelPreviousGesture, finishPreviousGesture;
2398 bool sendEvents =
2399 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2400 if (!sendEvents) {
2401 return;
2402 }
2403 if (finishPreviousGesture) {
2404 cancelPreviousGesture = false;
2405 }
2406
2407 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002408 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002409 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 if (finishPreviousGesture || cancelPreviousGesture) {
2411 mPointerController->clearSpots();
2412 }
2413
Michael Wright227c5542020-07-02 18:30:52 +01002414 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002415 setTouchSpots(mPointerGesture.currentGestureCoords,
2416 mPointerGesture.currentGestureIdToIndex,
2417 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 }
2419 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002420 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002421 }
2422
2423 // Show or hide the pointer if needed.
2424 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002425 case PointerGesture::Mode::NEUTRAL:
2426 case PointerGesture::Mode::QUIET:
2427 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2428 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002430 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431 }
2432 break;
Michael Wright227c5542020-07-02 18:30:52 +01002433 case PointerGesture::Mode::TAP:
2434 case PointerGesture::Mode::TAP_DRAG:
2435 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2436 case PointerGesture::Mode::HOVER:
2437 case PointerGesture::Mode::PRESS:
2438 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002439 // Unfade the pointer when the current gesture manipulates the
2440 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002441 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 break;
Michael Wright227c5542020-07-02 18:30:52 +01002443 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002444 // Fade the pointer when the current gesture manipulates a different
2445 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002446 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002447 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002449 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 }
2451 break;
2452 }
2453
2454 // Send events!
2455 int32_t metaState = getContext()->getGlobalMetaState();
2456 int32_t buttonState = mCurrentCookedState.buttonState;
2457
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002458 uint32_t flags = 0;
2459
2460 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2461 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2462 }
2463
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 // Update last coordinates of pointers that have moved so that we observe the new
2465 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002466 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2467 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2468 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2469 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2470 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2471 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 bool moveNeeded = false;
2473 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2474 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2475 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2476 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2477 mPointerGesture.lastGestureIdBits.value);
2478 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2479 mPointerGesture.currentGestureCoords,
2480 mPointerGesture.currentGestureIdToIndex,
2481 mPointerGesture.lastGestureProperties,
2482 mPointerGesture.lastGestureCoords,
2483 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2484 if (buttonState != mLastCookedState.buttonState) {
2485 moveNeeded = true;
2486 }
2487 }
2488
2489 // Send motion events for all pointers that went up or were canceled.
2490 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2491 if (!dispatchedGestureIdBits.isEmpty()) {
2492 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002493 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2494 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002495 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2496 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2497 mPointerGesture.downTime);
2498
2499 dispatchedGestureIdBits.clear();
2500 } else {
2501 BitSet32 upGestureIdBits;
2502 if (finishPreviousGesture) {
2503 upGestureIdBits = dispatchedGestureIdBits;
2504 } else {
2505 upGestureIdBits.value =
2506 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2507 }
2508 while (!upGestureIdBits.isEmpty()) {
2509 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2510
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002511 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002512 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002513 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 mPointerGesture.lastGestureCoords,
2515 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2516 0, mPointerGesture.downTime);
2517
2518 dispatchedGestureIdBits.clearBit(id);
2519 }
2520 }
2521 }
2522
2523 // Send motion events for all pointers that moved.
2524 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002525 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002526 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002527 mPointerGesture.currentGestureProperties,
2528 mPointerGesture.currentGestureCoords,
2529 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2530 mPointerGesture.downTime);
2531 }
2532
2533 // Send motion events for all pointers that went down.
2534 if (down) {
2535 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2536 ~dispatchedGestureIdBits.value);
2537 while (!downGestureIdBits.isEmpty()) {
2538 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2539 dispatchedGestureIdBits.markBit(id);
2540
2541 if (dispatchedGestureIdBits.count() == 1) {
2542 mPointerGesture.downTime = when;
2543 }
2544
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002545 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002546 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002547 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002548 mPointerGesture.currentGestureCoords,
2549 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2550 0, mPointerGesture.downTime);
2551 }
2552 }
2553
2554 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002555 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002556 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2557 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002558 mPointerGesture.currentGestureProperties,
2559 mPointerGesture.currentGestureCoords,
2560 mPointerGesture.currentGestureIdToIndex,
2561 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2562 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2563 // Synthesize a hover move event after all pointers go up to indicate that
2564 // the pointer is hovering again even if the user is not currently touching
2565 // the touch pad. This ensures that a view will receive a fresh hover enter
2566 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002567 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002568
2569 PointerProperties pointerProperties;
2570 pointerProperties.clear();
2571 pointerProperties.id = 0;
2572 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2573
2574 PointerCoords pointerCoords;
2575 pointerCoords.clear();
2576 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2577 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2578
2579 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002580 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002581 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002582 metaState, buttonState, MotionClassification::NONE,
2583 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2584 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002585 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002586 }
2587
2588 // Update state.
2589 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2590 if (!down) {
2591 mPointerGesture.lastGestureIdBits.clear();
2592 } else {
2593 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2594 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2595 uint32_t id = idBits.clearFirstMarkedBit();
2596 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2597 mPointerGesture.lastGestureProperties[index].copyFrom(
2598 mPointerGesture.currentGestureProperties[index]);
2599 mPointerGesture.lastGestureCoords[index].copyFrom(
2600 mPointerGesture.currentGestureCoords[index]);
2601 mPointerGesture.lastGestureIdToIndex[id] = index;
2602 }
2603 }
2604}
2605
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002606void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002607 // Cancel previously dispatches pointers.
2608 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2609 int32_t metaState = getContext()->getGlobalMetaState();
2610 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002611 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2612 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002613 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2614 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2615 0, 0, mPointerGesture.downTime);
2616 }
2617
2618 // Reset the current pointer gesture.
2619 mPointerGesture.reset();
2620 mPointerVelocityControl.reset();
2621
2622 // Remove any current spots.
2623 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002624 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002625 mPointerController->clearSpots();
2626 }
2627}
2628
2629bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2630 bool* outFinishPreviousGesture, bool isTimeout) {
2631 *outCancelPreviousGesture = false;
2632 *outFinishPreviousGesture = false;
2633
2634 // Handle TAP timeout.
2635 if (isTimeout) {
2636#if DEBUG_GESTURES
2637 ALOGD("Gestures: Processing timeout");
2638#endif
2639
Michael Wright227c5542020-07-02 18:30:52 +01002640 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002641 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2642 // The tap/drag timeout has not yet expired.
2643 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2644 mConfig.pointerGestureTapDragInterval);
2645 } else {
2646 // The tap is finished.
2647#if DEBUG_GESTURES
2648 ALOGD("Gestures: TAP finished");
2649#endif
2650 *outFinishPreviousGesture = true;
2651
2652 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002653 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002654 mPointerGesture.currentGestureIdBits.clear();
2655
2656 mPointerVelocityControl.reset();
2657 return true;
2658 }
2659 }
2660
2661 // We did not handle this timeout.
2662 return false;
2663 }
2664
2665 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2666 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2667
2668 // Update the velocity tracker.
2669 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002670 std::vector<VelocityTracker::Position> positions;
2671 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002672 uint32_t id = idBits.clearFirstMarkedBit();
2673 const RawPointerData::Pointer& pointer =
2674 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002675 float x = pointer.x * mPointerXMovementScale;
2676 float y = pointer.y * mPointerYMovementScale;
2677 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002678 }
2679 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2680 positions);
2681 }
2682
2683 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2684 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002685 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2686 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2687 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002688 mPointerGesture.resetTap();
2689 }
2690
2691 // Pick a new active touch id if needed.
2692 // Choose an arbitrary pointer that just went down, if there is one.
2693 // Otherwise choose an arbitrary remaining pointer.
2694 // This guarantees we always have an active touch id when there is at least one pointer.
2695 // We keep the same active touch id for as long as possible.
2696 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2697 int32_t activeTouchId = lastActiveTouchId;
2698 if (activeTouchId < 0) {
2699 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2700 activeTouchId = mPointerGesture.activeTouchId =
2701 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2702 mPointerGesture.firstTouchTime = when;
2703 }
2704 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2705 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2706 activeTouchId = mPointerGesture.activeTouchId =
2707 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2708 } else {
2709 activeTouchId = mPointerGesture.activeTouchId = -1;
2710 }
2711 }
2712
2713 // Determine whether we are in quiet time.
2714 bool isQuietTime = false;
2715 if (activeTouchId < 0) {
2716 mPointerGesture.resetQuietTime();
2717 } else {
2718 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2719 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002720 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2721 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2722 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002723 currentFingerCount < 2) {
2724 // Enter quiet time when exiting swipe or freeform state.
2725 // This is to prevent accidentally entering the hover state and flinging the
2726 // pointer when finishing a swipe and there is still one pointer left onscreen.
2727 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002728 } else if (mPointerGesture.lastGestureMode ==
2729 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002730 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2731 // Enter quiet time when releasing the button and there are still two or more
2732 // fingers down. This may indicate that one finger was used to press the button
2733 // but it has not gone up yet.
2734 isQuietTime = true;
2735 }
2736 if (isQuietTime) {
2737 mPointerGesture.quietTime = when;
2738 }
2739 }
2740 }
2741
2742 // Switch states based on button and pointer state.
2743 if (isQuietTime) {
2744 // Case 1: Quiet time. (QUIET)
2745#if DEBUG_GESTURES
2746 ALOGD("Gestures: QUIET for next %0.3fms",
2747 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2748#endif
Michael Wright227c5542020-07-02 18:30:52 +01002749 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002750 *outFinishPreviousGesture = true;
2751 }
2752
2753 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002754 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002755 mPointerGesture.currentGestureIdBits.clear();
2756
2757 mPointerVelocityControl.reset();
2758 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2759 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2760 // The pointer follows the active touch point.
2761 // Emit DOWN, MOVE, UP events at the pointer location.
2762 //
2763 // Only the active touch matters; other fingers are ignored. This policy helps
2764 // to handle the case where the user places a second finger on the touch pad
2765 // to apply the necessary force to depress an integrated button below the surface.
2766 // We don't want the second finger to be delivered to applications.
2767 //
2768 // For this to work well, we need to make sure to track the pointer that is really
2769 // active. If the user first puts one finger down to click then adds another
2770 // finger to drag then the active pointer should switch to the finger that is
2771 // being dragged.
2772#if DEBUG_GESTURES
2773 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2774 "currentFingerCount=%d",
2775 activeTouchId, currentFingerCount);
2776#endif
2777 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002778 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002779 *outFinishPreviousGesture = true;
2780 mPointerGesture.activeGestureId = 0;
2781 }
2782
2783 // Switch pointers if needed.
2784 // Find the fastest pointer and follow it.
2785 if (activeTouchId >= 0 && currentFingerCount > 1) {
2786 int32_t bestId = -1;
2787 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2788 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2789 uint32_t id = idBits.clearFirstMarkedBit();
2790 float vx, vy;
2791 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2792 float speed = hypotf(vx, vy);
2793 if (speed > bestSpeed) {
2794 bestId = id;
2795 bestSpeed = speed;
2796 }
2797 }
2798 }
2799 if (bestId >= 0 && bestId != activeTouchId) {
2800 mPointerGesture.activeTouchId = activeTouchId = bestId;
2801#if DEBUG_GESTURES
2802 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2803 "bestId=%d, bestSpeed=%0.3f",
2804 bestId, bestSpeed);
2805#endif
2806 }
2807 }
2808
2809 float deltaX = 0, deltaY = 0;
2810 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2811 const RawPointerData::Pointer& currentPointer =
2812 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2813 const RawPointerData::Pointer& lastPointer =
2814 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2815 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2816 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2817
2818 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2819 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2820
2821 // Move the pointer using a relative motion.
2822 // When using spots, the click will occur at the position of the anchor
2823 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002824 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825 } else {
2826 mPointerVelocityControl.reset();
2827 }
2828
Prabir Pradhand7482e72021-03-09 13:54:55 -08002829 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830
Michael Wright227c5542020-07-02 18:30:52 +01002831 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002832 mPointerGesture.currentGestureIdBits.clear();
2833 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2834 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2835 mPointerGesture.currentGestureProperties[0].clear();
2836 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2837 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2838 mPointerGesture.currentGestureCoords[0].clear();
2839 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2840 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2841 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2842 } else if (currentFingerCount == 0) {
2843 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002844 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002845 *outFinishPreviousGesture = true;
2846 }
2847
2848 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2849 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2850 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002851 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2852 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002853 lastFingerCount == 1) {
2854 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002855 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2857 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2858#if DEBUG_GESTURES
2859 ALOGD("Gestures: TAP");
2860#endif
2861
2862 mPointerGesture.tapUpTime = when;
2863 getContext()->requestTimeoutAtTime(when +
2864 mConfig.pointerGestureTapDragInterval);
2865
2866 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002867 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002868 mPointerGesture.currentGestureIdBits.clear();
2869 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2870 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2871 mPointerGesture.currentGestureProperties[0].clear();
2872 mPointerGesture.currentGestureProperties[0].id =
2873 mPointerGesture.activeGestureId;
2874 mPointerGesture.currentGestureProperties[0].toolType =
2875 AMOTION_EVENT_TOOL_TYPE_FINGER;
2876 mPointerGesture.currentGestureCoords[0].clear();
2877 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2878 mPointerGesture.tapX);
2879 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2880 mPointerGesture.tapY);
2881 mPointerGesture.currentGestureCoords[0]
2882 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2883
2884 tapped = true;
2885 } else {
2886#if DEBUG_GESTURES
2887 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2888 y - mPointerGesture.tapY);
2889#endif
2890 }
2891 } else {
2892#if DEBUG_GESTURES
2893 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2894 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2895 (when - mPointerGesture.tapDownTime) * 0.000001f);
2896 } else {
2897 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2898 }
2899#endif
2900 }
2901 }
2902
2903 mPointerVelocityControl.reset();
2904
2905 if (!tapped) {
2906#if DEBUG_GESTURES
2907 ALOGD("Gestures: NEUTRAL");
2908#endif
2909 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002910 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002911 mPointerGesture.currentGestureIdBits.clear();
2912 }
2913 } else if (currentFingerCount == 1) {
2914 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2915 // The pointer follows the active touch point.
2916 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2917 // When in TAP_DRAG, emit MOVE events at the pointer location.
2918 ALOG_ASSERT(activeTouchId >= 0);
2919
Michael Wright227c5542020-07-02 18:30:52 +01002920 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2921 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002923 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002924 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2925 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002926 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002927 } else {
2928#if DEBUG_GESTURES
2929 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2930 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2931#endif
2932 }
2933 } else {
2934#if DEBUG_GESTURES
2935 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2936 (when - mPointerGesture.tapUpTime) * 0.000001f);
2937#endif
2938 }
Michael Wright227c5542020-07-02 18:30:52 +01002939 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2940 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002941 }
2942
2943 float deltaX = 0, deltaY = 0;
2944 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2945 const RawPointerData::Pointer& currentPointer =
2946 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2947 const RawPointerData::Pointer& lastPointer =
2948 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2949 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2950 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2951
2952 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2953 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2954
2955 // Move the pointer using a relative motion.
2956 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002957 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958 } else {
2959 mPointerVelocityControl.reset();
2960 }
2961
2962 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002963 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002964#if DEBUG_GESTURES
2965 ALOGD("Gestures: TAP_DRAG");
2966#endif
2967 down = true;
2968 } else {
2969#if DEBUG_GESTURES
2970 ALOGD("Gestures: HOVER");
2971#endif
Michael Wright227c5542020-07-02 18:30:52 +01002972 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 *outFinishPreviousGesture = true;
2974 }
2975 mPointerGesture.activeGestureId = 0;
2976 down = false;
2977 }
2978
Prabir Pradhand7482e72021-03-09 13:54:55 -08002979 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002980
2981 mPointerGesture.currentGestureIdBits.clear();
2982 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2983 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2984 mPointerGesture.currentGestureProperties[0].clear();
2985 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2986 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2987 mPointerGesture.currentGestureCoords[0].clear();
2988 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2989 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2990 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2991 down ? 1.0f : 0.0f);
2992
2993 if (lastFingerCount == 0 && currentFingerCount != 0) {
2994 mPointerGesture.resetTap();
2995 mPointerGesture.tapDownTime = when;
2996 mPointerGesture.tapX = x;
2997 mPointerGesture.tapY = y;
2998 }
2999 } else {
3000 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3001 // We need to provide feedback for each finger that goes down so we cannot wait
3002 // for the fingers to move before deciding what to do.
3003 //
3004 // The ambiguous case is deciding what to do when there are two fingers down but they
3005 // have not moved enough to determine whether they are part of a drag or part of a
3006 // freeform gesture, or just a press or long-press at the pointer location.
3007 //
3008 // When there are two fingers we start with the PRESS hypothesis and we generate a
3009 // down at the pointer location.
3010 //
3011 // When the two fingers move enough or when additional fingers are added, we make
3012 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3013 ALOG_ASSERT(activeTouchId >= 0);
3014
3015 bool settled = when >=
3016 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003017 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3018 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3019 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003020 *outFinishPreviousGesture = true;
3021 } else if (!settled && currentFingerCount > lastFingerCount) {
3022 // Additional pointers have gone down but not yet settled.
3023 // Reset the gesture.
3024#if DEBUG_GESTURES
3025 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3026 "settle time remaining %0.3fms",
3027 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3028 when) * 0.000001f);
3029#endif
3030 *outCancelPreviousGesture = true;
3031 } else {
3032 // Continue previous gesture.
3033 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3034 }
3035
3036 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003037 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003038 mPointerGesture.activeGestureId = 0;
3039 mPointerGesture.referenceIdBits.clear();
3040 mPointerVelocityControl.reset();
3041
3042 // Use the centroid and pointer location as the reference points for the gesture.
3043#if DEBUG_GESTURES
3044 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3045 "settle time remaining %0.3fms",
3046 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3047 when) * 0.000001f);
3048#endif
3049 mCurrentRawState.rawPointerData
3050 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3051 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003052 auto [x, y] = getMouseCursorPosition();
3053 mPointerGesture.referenceGestureX = x;
3054 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003055 }
3056
3057 // Clear the reference deltas for fingers not yet included in the reference calculation.
3058 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3059 ~mPointerGesture.referenceIdBits.value);
3060 !idBits.isEmpty();) {
3061 uint32_t id = idBits.clearFirstMarkedBit();
3062 mPointerGesture.referenceDeltas[id].dx = 0;
3063 mPointerGesture.referenceDeltas[id].dy = 0;
3064 }
3065 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3066
3067 // Add delta for all fingers and calculate a common movement delta.
3068 float commonDeltaX = 0, commonDeltaY = 0;
3069 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3070 mCurrentCookedState.fingerIdBits.value);
3071 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3072 bool first = (idBits == commonIdBits);
3073 uint32_t id = idBits.clearFirstMarkedBit();
3074 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3075 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3076 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3077 delta.dx += cpd.x - lpd.x;
3078 delta.dy += cpd.y - lpd.y;
3079
3080 if (first) {
3081 commonDeltaX = delta.dx;
3082 commonDeltaY = delta.dy;
3083 } else {
3084 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3085 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3086 }
3087 }
3088
3089 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003090 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003091 float dist[MAX_POINTER_ID + 1];
3092 int32_t distOverThreshold = 0;
3093 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3094 uint32_t id = idBits.clearFirstMarkedBit();
3095 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3096 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3097 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3098 distOverThreshold += 1;
3099 }
3100 }
3101
3102 // Only transition when at least two pointers have moved further than
3103 // the minimum distance threshold.
3104 if (distOverThreshold >= 2) {
3105 if (currentFingerCount > 2) {
3106 // There are more than two pointers, switch to FREEFORM.
3107#if DEBUG_GESTURES
3108 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3109 currentFingerCount);
3110#endif
3111 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003112 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003113 } else {
3114 // There are exactly two pointers.
3115 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3116 uint32_t id1 = idBits.clearFirstMarkedBit();
3117 uint32_t id2 = idBits.firstMarkedBit();
3118 const RawPointerData::Pointer& p1 =
3119 mCurrentRawState.rawPointerData.pointerForId(id1);
3120 const RawPointerData::Pointer& p2 =
3121 mCurrentRawState.rawPointerData.pointerForId(id2);
3122 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3123 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3124 // There are two pointers but they are too far apart for a SWIPE,
3125 // switch to FREEFORM.
3126#if DEBUG_GESTURES
3127 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3128 mutualDistance, mPointerGestureMaxSwipeWidth);
3129#endif
3130 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003131 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003132 } else {
3133 // There are two pointers. Wait for both pointers to start moving
3134 // before deciding whether this is a SWIPE or FREEFORM gesture.
3135 float dist1 = dist[id1];
3136 float dist2 = dist[id2];
3137 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3138 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3139 // Calculate the dot product of the displacement vectors.
3140 // When the vectors are oriented in approximately the same direction,
3141 // the angle betweeen them is near zero and the cosine of the angle
3142 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3143 // mag(v2).
3144 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3145 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3146 float dx1 = delta1.dx * mPointerXZoomScale;
3147 float dy1 = delta1.dy * mPointerYZoomScale;
3148 float dx2 = delta2.dx * mPointerXZoomScale;
3149 float dy2 = delta2.dy * mPointerYZoomScale;
3150 float dot = dx1 * dx2 + dy1 * dy2;
3151 float cosine = dot / (dist1 * dist2); // denominator always > 0
3152 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3153 // Pointers are moving in the same direction. Switch to SWIPE.
3154#if DEBUG_GESTURES
3155 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3156 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3157 "cosine %0.3f >= %0.3f",
3158 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3159 mConfig.pointerGestureMultitouchMinDistance, cosine,
3160 mConfig.pointerGestureSwipeTransitionAngleCosine);
3161#endif
Michael Wright227c5542020-07-02 18:30:52 +01003162 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003163 } else {
3164 // Pointers are moving in different directions. Switch to FREEFORM.
3165#if DEBUG_GESTURES
3166 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3167 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3168 "cosine %0.3f < %0.3f",
3169 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3170 mConfig.pointerGestureMultitouchMinDistance, cosine,
3171 mConfig.pointerGestureSwipeTransitionAngleCosine);
3172#endif
3173 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003174 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003175 }
3176 }
3177 }
3178 }
3179 }
Michael Wright227c5542020-07-02 18:30:52 +01003180 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003181 // Switch from SWIPE to FREEFORM if additional pointers go down.
3182 // Cancel previous gesture.
3183 if (currentFingerCount > 2) {
3184#if DEBUG_GESTURES
3185 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3186 currentFingerCount);
3187#endif
3188 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003189 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003190 }
3191 }
3192
3193 // Move the reference points based on the overall group motion of the fingers
3194 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003195 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003196 (commonDeltaX || commonDeltaY)) {
3197 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3198 uint32_t id = idBits.clearFirstMarkedBit();
3199 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3200 delta.dx = 0;
3201 delta.dy = 0;
3202 }
3203
3204 mPointerGesture.referenceTouchX += commonDeltaX;
3205 mPointerGesture.referenceTouchY += commonDeltaY;
3206
3207 commonDeltaX *= mPointerXMovementScale;
3208 commonDeltaY *= mPointerYMovementScale;
3209
3210 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3211 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3212
3213 mPointerGesture.referenceGestureX += commonDeltaX;
3214 mPointerGesture.referenceGestureY += commonDeltaY;
3215 }
3216
3217 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003218 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3219 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003220 // PRESS or SWIPE mode.
3221#if DEBUG_GESTURES
3222 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3223 "activeGestureId=%d, currentTouchPointerCount=%d",
3224 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3225#endif
3226 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3227
3228 mPointerGesture.currentGestureIdBits.clear();
3229 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3230 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3231 mPointerGesture.currentGestureProperties[0].clear();
3232 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3233 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3234 mPointerGesture.currentGestureCoords[0].clear();
3235 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3236 mPointerGesture.referenceGestureX);
3237 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3238 mPointerGesture.referenceGestureY);
3239 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003240 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003241 // FREEFORM mode.
3242#if DEBUG_GESTURES
3243 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3244 "activeGestureId=%d, currentTouchPointerCount=%d",
3245 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3246#endif
3247 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3248
3249 mPointerGesture.currentGestureIdBits.clear();
3250
3251 BitSet32 mappedTouchIdBits;
3252 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003253 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003254 // Initially, assign the active gesture id to the active touch point
3255 // if there is one. No other touch id bits are mapped yet.
3256 if (!*outCancelPreviousGesture) {
3257 mappedTouchIdBits.markBit(activeTouchId);
3258 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3259 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3260 mPointerGesture.activeGestureId;
3261 } else {
3262 mPointerGesture.activeGestureId = -1;
3263 }
3264 } else {
3265 // Otherwise, assume we mapped all touches from the previous frame.
3266 // Reuse all mappings that are still applicable.
3267 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3268 mCurrentCookedState.fingerIdBits.value;
3269 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3270
3271 // Check whether we need to choose a new active gesture id because the
3272 // current went went up.
3273 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3274 ~mCurrentCookedState.fingerIdBits.value);
3275 !upTouchIdBits.isEmpty();) {
3276 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3277 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3278 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3279 mPointerGesture.activeGestureId = -1;
3280 break;
3281 }
3282 }
3283 }
3284
3285#if DEBUG_GESTURES
3286 ALOGD("Gestures: FREEFORM follow up "
3287 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3288 "activeGestureId=%d",
3289 mappedTouchIdBits.value, usedGestureIdBits.value,
3290 mPointerGesture.activeGestureId);
3291#endif
3292
3293 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3294 for (uint32_t i = 0; i < currentFingerCount; i++) {
3295 uint32_t touchId = idBits.clearFirstMarkedBit();
3296 uint32_t gestureId;
3297 if (!mappedTouchIdBits.hasBit(touchId)) {
3298 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3299 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3300#if DEBUG_GESTURES
3301 ALOGD("Gestures: FREEFORM "
3302 "new mapping for touch id %d -> gesture id %d",
3303 touchId, gestureId);
3304#endif
3305 } else {
3306 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3307#if DEBUG_GESTURES
3308 ALOGD("Gestures: FREEFORM "
3309 "existing mapping for touch id %d -> gesture id %d",
3310 touchId, gestureId);
3311#endif
3312 }
3313 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3314 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3315
3316 const RawPointerData::Pointer& pointer =
3317 mCurrentRawState.rawPointerData.pointerForId(touchId);
3318 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3319 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3320 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3321
3322 mPointerGesture.currentGestureProperties[i].clear();
3323 mPointerGesture.currentGestureProperties[i].id = gestureId;
3324 mPointerGesture.currentGestureProperties[i].toolType =
3325 AMOTION_EVENT_TOOL_TYPE_FINGER;
3326 mPointerGesture.currentGestureCoords[i].clear();
3327 mPointerGesture.currentGestureCoords[i]
3328 .setAxisValue(AMOTION_EVENT_AXIS_X,
3329 mPointerGesture.referenceGestureX + deltaX);
3330 mPointerGesture.currentGestureCoords[i]
3331 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3332 mPointerGesture.referenceGestureY + deltaY);
3333 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3334 1.0f);
3335 }
3336
3337 if (mPointerGesture.activeGestureId < 0) {
3338 mPointerGesture.activeGestureId =
3339 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3340#if DEBUG_GESTURES
3341 ALOGD("Gestures: FREEFORM new "
3342 "activeGestureId=%d",
3343 mPointerGesture.activeGestureId);
3344#endif
3345 }
3346 }
3347 }
3348
3349 mPointerController->setButtonState(mCurrentRawState.buttonState);
3350
3351#if DEBUG_GESTURES
3352 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3353 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3354 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3355 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3356 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3357 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3358 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3359 uint32_t id = idBits.clearFirstMarkedBit();
3360 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3361 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3362 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3363 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3364 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3365 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3366 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3367 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3368 }
3369 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3370 uint32_t id = idBits.clearFirstMarkedBit();
3371 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3372 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3373 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3374 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3375 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3376 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3377 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3378 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3379 }
3380#endif
3381 return true;
3382}
3383
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003384void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003385 mPointerSimple.currentCoords.clear();
3386 mPointerSimple.currentProperties.clear();
3387
3388 bool down, hovering;
3389 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3390 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3391 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003392 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3393 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003394
3395 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3396 down = !hovering;
3397
Prabir Pradhand7482e72021-03-09 13:54:55 -08003398 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003399 mPointerSimple.currentCoords.copyFrom(
3400 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3401 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3402 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3403 mPointerSimple.currentProperties.id = 0;
3404 mPointerSimple.currentProperties.toolType =
3405 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3406 } else {
3407 down = false;
3408 hovering = false;
3409 }
3410
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003411 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003412}
3413
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003414void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3415 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003416}
3417
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003418void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003419 mPointerSimple.currentCoords.clear();
3420 mPointerSimple.currentProperties.clear();
3421
3422 bool down, hovering;
3423 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3424 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3425 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3426 float deltaX = 0, deltaY = 0;
3427 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3428 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3429 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3430 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3431 mPointerXMovementScale;
3432 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3433 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3434 mPointerYMovementScale;
3435
3436 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3437 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3438
Prabir Pradhand7482e72021-03-09 13:54:55 -08003439 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003440 } else {
3441 mPointerVelocityControl.reset();
3442 }
3443
3444 down = isPointerDown(mCurrentRawState.buttonState);
3445 hovering = !down;
3446
Prabir Pradhand7482e72021-03-09 13:54:55 -08003447 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003448 mPointerSimple.currentCoords.copyFrom(
3449 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3450 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3451 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3452 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3453 hovering ? 0.0f : 1.0f);
3454 mPointerSimple.currentProperties.id = 0;
3455 mPointerSimple.currentProperties.toolType =
3456 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3457 } else {
3458 mPointerVelocityControl.reset();
3459
3460 down = false;
3461 hovering = false;
3462 }
3463
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003464 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003465}
3466
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003467void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3468 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469
3470 mPointerVelocityControl.reset();
3471}
3472
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003473void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3474 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003475 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003476
3477 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003478 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003479 mPointerController->clearSpots();
3480 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003481 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003482 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003483 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003484 }
Garfield Tan9514d782020-11-10 16:37:23 -08003485 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003486
Prabir Pradhand7482e72021-03-09 13:54:55 -08003487 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003488
3489 if (mPointerSimple.down && !down) {
3490 mPointerSimple.down = false;
3491
3492 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003493 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3494 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003495 mLastRawState.buttonState, MotionClassification::NONE,
3496 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3497 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3498 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3499 /* videoFrames */ {});
3500 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003501 }
3502
3503 if (mPointerSimple.hovering && !hovering) {
3504 mPointerSimple.hovering = false;
3505
3506 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003507 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3508 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3509 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003510 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3511 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3512 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3513 /* videoFrames */ {});
3514 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515 }
3516
3517 if (down) {
3518 if (!mPointerSimple.down) {
3519 mPointerSimple.down = true;
3520 mPointerSimple.downTime = when;
3521
3522 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003523 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003524 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3525 metaState, mCurrentRawState.buttonState,
3526 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3527 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3528 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3529 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3530 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003531 }
3532
3533 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003534 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3535 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003536 mCurrentRawState.buttonState, MotionClassification::NONE,
3537 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3538 &mPointerSimple.currentCoords, mOrientedXPrecision,
3539 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3540 mPointerSimple.downTime, /* videoFrames */ {});
3541 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003542 }
3543
3544 if (hovering) {
3545 if (!mPointerSimple.hovering) {
3546 mPointerSimple.hovering = true;
3547
3548 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003549 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003550 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3551 metaState, mCurrentRawState.buttonState,
3552 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3553 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3554 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3555 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3556 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003557 }
3558
3559 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003560 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3561 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3562 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003563 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3564 &mPointerSimple.currentCoords, mOrientedXPrecision,
3565 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3566 mPointerSimple.downTime, /* videoFrames */ {});
3567 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003568 }
3569
3570 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3571 float vscroll = mCurrentRawState.rawVScroll;
3572 float hscroll = mCurrentRawState.rawHScroll;
3573 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3574 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3575
3576 // Send scroll.
3577 PointerCoords pointerCoords;
3578 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3579 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3580 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3581
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003582 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3583 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003584 mCurrentRawState.buttonState, MotionClassification::NONE,
3585 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3586 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3587 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3588 /* videoFrames */ {});
3589 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590 }
3591
3592 // Save state.
3593 if (down || hovering) {
3594 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3595 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3596 } else {
3597 mPointerSimple.reset();
3598 }
3599}
3600
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003601void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003602 mPointerSimple.currentCoords.clear();
3603 mPointerSimple.currentProperties.clear();
3604
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003605 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606}
3607
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003608void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3609 uint32_t source, int32_t action, int32_t actionButton,
3610 int32_t flags, int32_t metaState, int32_t buttonState,
3611 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003612 const PointerCoords* coords, const uint32_t* idToIndex,
3613 BitSet32 idBits, int32_t changedId, float xPrecision,
3614 float yPrecision, nsecs_t downTime) {
3615 PointerCoords pointerCoords[MAX_POINTERS];
3616 PointerProperties pointerProperties[MAX_POINTERS];
3617 uint32_t pointerCount = 0;
3618 while (!idBits.isEmpty()) {
3619 uint32_t id = idBits.clearFirstMarkedBit();
3620 uint32_t index = idToIndex[id];
3621 pointerProperties[pointerCount].copyFrom(properties[index]);
3622 pointerCoords[pointerCount].copyFrom(coords[index]);
3623
3624 if (changedId >= 0 && id == uint32_t(changedId)) {
3625 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3626 }
3627
3628 pointerCount += 1;
3629 }
3630
3631 ALOG_ASSERT(pointerCount != 0);
3632
3633 if (changedId >= 0 && pointerCount == 1) {
3634 // Replace initial down and final up action.
3635 // We can compare the action without masking off the changed pointer index
3636 // because we know the index is 0.
3637 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3638 action = AMOTION_EVENT_ACTION_DOWN;
3639 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003640 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3641 action = AMOTION_EVENT_ACTION_CANCEL;
3642 } else {
3643 action = AMOTION_EVENT_ACTION_UP;
3644 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003645 } else {
3646 // Can't happen.
3647 ALOG_ASSERT(false);
3648 }
3649 }
3650 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3651 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003652 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003653 auto [x, y] = getMouseCursorPosition();
3654 xCursorPosition = x;
3655 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003656 }
3657 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3658 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003659 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003660 std::for_each(frames.begin(), frames.end(),
3661 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003662 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3663 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003664 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3665 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3666 downTime, std::move(frames));
3667 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003668}
3669
3670bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3671 const PointerCoords* inCoords,
3672 const uint32_t* inIdToIndex,
3673 PointerProperties* outProperties,
3674 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3675 BitSet32 idBits) const {
3676 bool changed = false;
3677 while (!idBits.isEmpty()) {
3678 uint32_t id = idBits.clearFirstMarkedBit();
3679 uint32_t inIndex = inIdToIndex[id];
3680 uint32_t outIndex = outIdToIndex[id];
3681
3682 const PointerProperties& curInProperties = inProperties[inIndex];
3683 const PointerCoords& curInCoords = inCoords[inIndex];
3684 PointerProperties& curOutProperties = outProperties[outIndex];
3685 PointerCoords& curOutCoords = outCoords[outIndex];
3686
3687 if (curInProperties != curOutProperties) {
3688 curOutProperties.copyFrom(curInProperties);
3689 changed = true;
3690 }
3691
3692 if (curInCoords != curOutCoords) {
3693 curOutCoords.copyFrom(curInCoords);
3694 changed = true;
3695 }
3696 }
3697 return changed;
3698}
3699
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003700void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3701 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3702 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003703}
3704
Arthur Hung4197f6b2020-03-16 15:39:59 +08003705// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003706void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003707 // Scale to surface coordinate.
3708 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3709 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3710
arthurhunga36b28e2020-12-29 20:28:15 +08003711 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3712 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3713
Arthur Hung4197f6b2020-03-16 15:39:59 +08003714 // Rotate to surface coordinate.
3715 // 0 - no swap and reverse.
3716 // 90 - swap x/y and reverse y.
3717 // 180 - reverse x, y.
3718 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003719 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003720 case DISPLAY_ORIENTATION_0:
3721 x = xScaled + mXTranslate;
3722 y = yScaled + mYTranslate;
3723 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003724 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003725 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003726 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003727 break;
3728 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003729 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3730 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003731 break;
3732 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003733 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003734 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003735 break;
3736 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003737 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003738 }
3739}
3740
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003741bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003742 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3743 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3744
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003745 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003746 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003747 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003748 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003749}
3750
3751const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3752 for (const VirtualKey& virtualKey : mVirtualKeys) {
3753#if DEBUG_VIRTUAL_KEYS
3754 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3755 "left=%d, top=%d, right=%d, bottom=%d",
3756 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3757 virtualKey.hitRight, virtualKey.hitBottom);
3758#endif
3759
3760 if (virtualKey.isHit(x, y)) {
3761 return &virtualKey;
3762 }
3763 }
3764
3765 return nullptr;
3766}
3767
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003768void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3769 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3770 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003771
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003772 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003773
3774 if (currentPointerCount == 0) {
3775 // No pointers to assign.
3776 return;
3777 }
3778
3779 if (lastPointerCount == 0) {
3780 // All pointers are new.
3781 for (uint32_t i = 0; i < currentPointerCount; i++) {
3782 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003783 current.rawPointerData.pointers[i].id = id;
3784 current.rawPointerData.idToIndex[id] = i;
3785 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003786 }
3787 return;
3788 }
3789
3790 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003791 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003792 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003793 uint32_t id = last.rawPointerData.pointers[0].id;
3794 current.rawPointerData.pointers[0].id = id;
3795 current.rawPointerData.idToIndex[id] = 0;
3796 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003797 return;
3798 }
3799
3800 // General case.
3801 // We build a heap of squared euclidean distances between current and last pointers
3802 // associated with the current and last pointer indices. Then, we find the best
3803 // match (by distance) for each current pointer.
3804 // The pointers must have the same tool type but it is possible for them to
3805 // transition from hovering to touching or vice-versa while retaining the same id.
3806 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3807
3808 uint32_t heapSize = 0;
3809 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3810 currentPointerIndex++) {
3811 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3812 lastPointerIndex++) {
3813 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003814 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003815 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003816 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003817 if (currentPointer.toolType == lastPointer.toolType) {
3818 int64_t deltaX = currentPointer.x - lastPointer.x;
3819 int64_t deltaY = currentPointer.y - lastPointer.y;
3820
3821 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3822
3823 // Insert new element into the heap (sift up).
3824 heap[heapSize].currentPointerIndex = currentPointerIndex;
3825 heap[heapSize].lastPointerIndex = lastPointerIndex;
3826 heap[heapSize].distance = distance;
3827 heapSize += 1;
3828 }
3829 }
3830 }
3831
3832 // Heapify
3833 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3834 startIndex -= 1;
3835 for (uint32_t parentIndex = startIndex;;) {
3836 uint32_t childIndex = parentIndex * 2 + 1;
3837 if (childIndex >= heapSize) {
3838 break;
3839 }
3840
3841 if (childIndex + 1 < heapSize &&
3842 heap[childIndex + 1].distance < heap[childIndex].distance) {
3843 childIndex += 1;
3844 }
3845
3846 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3847 break;
3848 }
3849
3850 swap(heap[parentIndex], heap[childIndex]);
3851 parentIndex = childIndex;
3852 }
3853 }
3854
3855#if DEBUG_POINTER_ASSIGNMENT
3856 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3857 for (size_t i = 0; i < heapSize; i++) {
3858 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3859 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3860 }
3861#endif
3862
3863 // Pull matches out by increasing order of distance.
3864 // To avoid reassigning pointers that have already been matched, the loop keeps track
3865 // of which last and current pointers have been matched using the matchedXXXBits variables.
3866 // It also tracks the used pointer id bits.
3867 BitSet32 matchedLastBits(0);
3868 BitSet32 matchedCurrentBits(0);
3869 BitSet32 usedIdBits(0);
3870 bool first = true;
3871 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3872 while (heapSize > 0) {
3873 if (first) {
3874 // The first time through the loop, we just consume the root element of
3875 // the heap (the one with smallest distance).
3876 first = false;
3877 } else {
3878 // Previous iterations consumed the root element of the heap.
3879 // Pop root element off of the heap (sift down).
3880 heap[0] = heap[heapSize];
3881 for (uint32_t parentIndex = 0;;) {
3882 uint32_t childIndex = parentIndex * 2 + 1;
3883 if (childIndex >= heapSize) {
3884 break;
3885 }
3886
3887 if (childIndex + 1 < heapSize &&
3888 heap[childIndex + 1].distance < heap[childIndex].distance) {
3889 childIndex += 1;
3890 }
3891
3892 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3893 break;
3894 }
3895
3896 swap(heap[parentIndex], heap[childIndex]);
3897 parentIndex = childIndex;
3898 }
3899
3900#if DEBUG_POINTER_ASSIGNMENT
3901 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003902 for (size_t j = 0; j < heapSize; j++) {
3903 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3904 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003905 }
3906#endif
3907 }
3908
3909 heapSize -= 1;
3910
3911 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3912 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3913
3914 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3915 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3916
3917 matchedCurrentBits.markBit(currentPointerIndex);
3918 matchedLastBits.markBit(lastPointerIndex);
3919
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003920 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3921 current.rawPointerData.pointers[currentPointerIndex].id = id;
3922 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3923 current.rawPointerData.markIdBit(id,
3924 current.rawPointerData.isHovering(
3925 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003926 usedIdBits.markBit(id);
3927
3928#if DEBUG_POINTER_ASSIGNMENT
3929 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3930 ", distance=%" PRIu64,
3931 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3932#endif
3933 break;
3934 }
3935 }
3936
3937 // Assign fresh ids to pointers that were not matched in the process.
3938 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3939 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3940 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3941
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003942 current.rawPointerData.pointers[currentPointerIndex].id = id;
3943 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3944 current.rawPointerData.markIdBit(id,
3945 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003946
3947#if DEBUG_POINTER_ASSIGNMENT
3948 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3949#endif
3950 }
3951}
3952
3953int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3954 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3955 return AKEY_STATE_VIRTUAL;
3956 }
3957
3958 for (const VirtualKey& virtualKey : mVirtualKeys) {
3959 if (virtualKey.keyCode == keyCode) {
3960 return AKEY_STATE_UP;
3961 }
3962 }
3963
3964 return AKEY_STATE_UNKNOWN;
3965}
3966
3967int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3968 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3969 return AKEY_STATE_VIRTUAL;
3970 }
3971
3972 for (const VirtualKey& virtualKey : mVirtualKeys) {
3973 if (virtualKey.scanCode == scanCode) {
3974 return AKEY_STATE_UP;
3975 }
3976 }
3977
3978 return AKEY_STATE_UNKNOWN;
3979}
3980
3981bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3982 const int32_t* keyCodes, uint8_t* outFlags) {
3983 for (const VirtualKey& virtualKey : mVirtualKeys) {
3984 for (size_t i = 0; i < numCodes; i++) {
3985 if (virtualKey.keyCode == keyCodes[i]) {
3986 outFlags[i] = 1;
3987 }
3988 }
3989 }
3990
3991 return true;
3992}
3993
3994std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3995 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003996 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003997 return std::make_optional(mPointerController->getDisplayId());
3998 } else {
3999 return std::make_optional(mViewport.displayId);
4000 }
4001 }
4002 return std::nullopt;
4003}
4004
Prabir Pradhand7482e72021-03-09 13:54:55 -08004005void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
4006 if (isPerWindowInputRotationEnabled()) {
4007 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4008 // space that is oriented with the viewport.
4009 rotateDelta(mViewport.orientation, &dx, &dy);
4010 }
4011
4012 mPointerController->move(dx, dy);
4013}
4014
4015std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4016 float x = 0;
4017 float y = 0;
4018 mPointerController->getPosition(&x, &y);
4019
4020 if (!isPerWindowInputRotationEnabled()) return {x, y};
4021 if (!mViewport.isValid()) return {x, y};
4022
4023 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4024 // to InputReader's un-rotated coordinate space.
4025 const int32_t orientation = getInverseRotation(mViewport.orientation);
4026 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4027 return {x, y};
4028}
4029
4030void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4031 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4032 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4033 // coordinate space that is oriented with the viewport.
4034 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4035 }
4036
4037 mPointerController->setPosition(x, y);
4038}
4039
4040void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4041 BitSet32 spotIdBits, int32_t displayId) {
4042 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4043
4044 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4045 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4046 float x = spotCoords[index].getX();
4047 float y = spotCoords[index].getY();
4048 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4049
4050 if (isPerWindowInputRotationEnabled()) {
4051 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4052 // coordinate space.
4053 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4054 }
4055
4056 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4057 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4058 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4059 }
4060
4061 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4062}
4063
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004064} // namespace android