blob: 4cc8f90a22d4a12aa037223fc11e7bc14ea1c157 [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 &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000606 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
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) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000779 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
780 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800781 if (mPointerController == nullptr) {
782 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700783 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000784 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800785 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
786 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700787 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100788 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700789 }
790
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700791 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700792 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
793 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800794 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700795 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
796
797 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800798 mXScale = float(mRawSurfaceWidth) / rawWidth;
799 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700800 mXTranslate = -mSurfaceLeft;
801 mYTranslate = -mSurfaceTop;
802 mXPrecision = 1.0f / mXScale;
803 mYPrecision = 1.0f / mYScale;
804
805 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
806 mOrientedRanges.x.source = mSource;
807 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
808 mOrientedRanges.y.source = mSource;
809
810 configureVirtualKeys();
811
812 // Scale factor for terms that are not oriented in a particular axis.
813 // If the pixels are square then xScale == yScale otherwise we fake it
814 // by choosing an average.
815 mGeometricScale = avg(mXScale, mYScale);
816
817 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800818 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700819
820 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100821 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700822 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
823 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
824 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
825 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
826 } else {
827 mSizeScale = 0.0f;
828 }
829
830 mOrientedRanges.haveTouchSize = true;
831 mOrientedRanges.haveToolSize = true;
832 mOrientedRanges.haveSize = true;
833
834 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
835 mOrientedRanges.touchMajor.source = mSource;
836 mOrientedRanges.touchMajor.min = 0;
837 mOrientedRanges.touchMajor.max = diagonalSize;
838 mOrientedRanges.touchMajor.flat = 0;
839 mOrientedRanges.touchMajor.fuzz = 0;
840 mOrientedRanges.touchMajor.resolution = 0;
841
842 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
843 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
844
845 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
846 mOrientedRanges.toolMajor.source = mSource;
847 mOrientedRanges.toolMajor.min = 0;
848 mOrientedRanges.toolMajor.max = diagonalSize;
849 mOrientedRanges.toolMajor.flat = 0;
850 mOrientedRanges.toolMajor.fuzz = 0;
851 mOrientedRanges.toolMajor.resolution = 0;
852
853 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
854 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
855
856 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
857 mOrientedRanges.size.source = mSource;
858 mOrientedRanges.size.min = 0;
859 mOrientedRanges.size.max = 1.0;
860 mOrientedRanges.size.flat = 0;
861 mOrientedRanges.size.fuzz = 0;
862 mOrientedRanges.size.resolution = 0;
863 } else {
864 mSizeScale = 0.0f;
865 }
866
867 // Pressure factors.
868 mPressureScale = 0;
869 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100870 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
871 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700872 if (mCalibration.havePressureScale) {
873 mPressureScale = mCalibration.pressureScale;
874 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
875 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
876 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
877 }
878 }
879
880 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
881 mOrientedRanges.pressure.source = mSource;
882 mOrientedRanges.pressure.min = 0;
883 mOrientedRanges.pressure.max = pressureMax;
884 mOrientedRanges.pressure.flat = 0;
885 mOrientedRanges.pressure.fuzz = 0;
886 mOrientedRanges.pressure.resolution = 0;
887
888 // Tilt
889 mTiltXCenter = 0;
890 mTiltXScale = 0;
891 mTiltYCenter = 0;
892 mTiltYScale = 0;
893 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
894 if (mHaveTilt) {
895 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
896 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
897 mTiltXScale = M_PI / 180;
898 mTiltYScale = M_PI / 180;
899
Tatsunosuke Tobita35e05532021-06-30 14:49:32 +0900900 if (mRawPointerAxes.tiltX.resolution) {
901 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
902 }
903 if (mRawPointerAxes.tiltY.resolution) {
904 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
905 }
906
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700907 mOrientedRanges.haveTilt = true;
908
909 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
910 mOrientedRanges.tilt.source = mSource;
911 mOrientedRanges.tilt.min = 0;
912 mOrientedRanges.tilt.max = M_PI_2;
913 mOrientedRanges.tilt.flat = 0;
914 mOrientedRanges.tilt.fuzz = 0;
915 mOrientedRanges.tilt.resolution = 0;
916 }
917
918 // Orientation
919 mOrientationScale = 0;
920 if (mHaveTilt) {
921 mOrientedRanges.haveOrientation = true;
922
923 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
924 mOrientedRanges.orientation.source = mSource;
925 mOrientedRanges.orientation.min = -M_PI;
926 mOrientedRanges.orientation.max = M_PI;
927 mOrientedRanges.orientation.flat = 0;
928 mOrientedRanges.orientation.fuzz = 0;
929 mOrientedRanges.orientation.resolution = 0;
930 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100931 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700932 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100933 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700934 if (mRawPointerAxes.orientation.valid) {
935 if (mRawPointerAxes.orientation.maxValue > 0) {
936 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
937 } else if (mRawPointerAxes.orientation.minValue < 0) {
938 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
939 } else {
940 mOrientationScale = 0;
941 }
942 }
943 }
944
945 mOrientedRanges.haveOrientation = true;
946
947 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
948 mOrientedRanges.orientation.source = mSource;
949 mOrientedRanges.orientation.min = -M_PI_2;
950 mOrientedRanges.orientation.max = M_PI_2;
951 mOrientedRanges.orientation.flat = 0;
952 mOrientedRanges.orientation.fuzz = 0;
953 mOrientedRanges.orientation.resolution = 0;
954 }
955
956 // Distance
957 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100958 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
959 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700960 if (mCalibration.haveDistanceScale) {
961 mDistanceScale = mCalibration.distanceScale;
962 } else {
963 mDistanceScale = 1.0f;
964 }
965 }
966
967 mOrientedRanges.haveDistance = true;
968
969 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
970 mOrientedRanges.distance.source = mSource;
971 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
972 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
973 mOrientedRanges.distance.flat = 0;
974 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
975 mOrientedRanges.distance.resolution = 0;
976 }
977
978 // Compute oriented precision, scales and ranges.
979 // Note that the maximum value reported is an inclusive maximum value so it is one
980 // unit less than the total width or height of surface.
981 switch (mSurfaceOrientation) {
982 case DISPLAY_ORIENTATION_90:
983 case DISPLAY_ORIENTATION_270:
984 mOrientedXPrecision = mYPrecision;
985 mOrientedYPrecision = mXPrecision;
986
987 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800988 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700989 mOrientedRanges.x.flat = 0;
990 mOrientedRanges.x.fuzz = 0;
991 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
992
993 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800994 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700995 mOrientedRanges.y.flat = 0;
996 mOrientedRanges.y.fuzz = 0;
997 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
998 break;
999
1000 default:
1001 mOrientedXPrecision = mXPrecision;
1002 mOrientedYPrecision = mYPrecision;
1003
1004 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001005 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001006 mOrientedRanges.x.flat = 0;
1007 mOrientedRanges.x.fuzz = 0;
1008 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1009
1010 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001011 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001012 mOrientedRanges.y.flat = 0;
1013 mOrientedRanges.y.fuzz = 0;
1014 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1015 break;
1016 }
1017
1018 // Location
1019 updateAffineTransformation();
1020
Michael Wright227c5542020-07-02 18:30:52 +01001021 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001022 // Compute pointer gesture detection parameters.
1023 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001024 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001025
1026 // Scale movements such that one whole swipe of the touch pad covers a
1027 // given area relative to the diagonal size of the display when no acceleration
1028 // is applied.
1029 // Assume that the touch pad has a square aspect ratio such that movements in
1030 // X and Y of the same number of raw units cover the same physical distance.
1031 mPointerXMovementScale =
1032 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1033 mPointerYMovementScale = mPointerXMovementScale;
1034
1035 // Scale zooms to cover a smaller range of the display than movements do.
1036 // This value determines the area around the pointer that is affected by freeform
1037 // pointer gestures.
1038 mPointerXZoomScale =
1039 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1040 mPointerYZoomScale = mPointerXZoomScale;
1041
1042 // Max width between pointers to detect a swipe gesture is more than some fraction
1043 // of the diagonal axis of the touch pad. Touches that are wider than this are
1044 // translated into freeform gestures.
1045 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1046
1047 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001048 const nsecs_t readTime = when; // synthetic event
1049 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001050 }
1051
1052 // Inform the dispatcher about the changes.
1053 *outResetNeeded = true;
1054 bumpGeneration();
1055 }
1056}
1057
1058void TouchInputMapper::dumpSurface(std::string& dump) {
1059 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001060 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1061 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1063 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001064 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1065 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1067 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1068 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1069 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1070 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1071}
1072
1073void TouchInputMapper::configureVirtualKeys() {
1074 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001075 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001076
1077 mVirtualKeys.clear();
1078
1079 if (virtualKeyDefinitions.size() == 0) {
1080 return;
1081 }
1082
1083 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1084 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1085 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1086 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1087
1088 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1089 VirtualKey virtualKey;
1090
1091 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1092 int32_t keyCode;
1093 int32_t dummyKeyMetaState;
1094 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001095 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1096 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001097 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1098 continue; // drop the key
1099 }
1100
1101 virtualKey.keyCode = keyCode;
1102 virtualKey.flags = flags;
1103
1104 // convert the key definition's display coordinates into touch coordinates for a hit box
1105 int32_t halfWidth = virtualKeyDefinition.width / 2;
1106 int32_t halfHeight = virtualKeyDefinition.height / 2;
1107
1108 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001109 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110 touchScreenLeft;
1111 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001112 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001114 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1115 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001117 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1118 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001119 touchScreenTop;
1120 mVirtualKeys.push_back(virtualKey);
1121 }
1122}
1123
1124void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1125 if (!mVirtualKeys.empty()) {
1126 dump += INDENT3 "Virtual Keys:\n";
1127
1128 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1129 const VirtualKey& virtualKey = mVirtualKeys[i];
1130 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1131 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1132 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1133 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1134 }
1135 }
1136}
1137
1138void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001139 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001140 Calibration& out = mCalibration;
1141
1142 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 String8 sizeCalibrationString;
1145 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1146 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001147 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001149 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001151 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001152 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001153 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001155 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001156 } else if (sizeCalibrationString != "default") {
1157 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1158 }
1159 }
1160
1161 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1162 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1163 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1164
1165 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 String8 pressureCalibrationString;
1168 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1169 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001172 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001173 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001174 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 } else if (pressureCalibrationString != "default") {
1176 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1177 pressureCalibrationString.string());
1178 }
1179 }
1180
1181 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1182
1183 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001185 String8 orientationCalibrationString;
1186 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1187 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 } else if (orientationCalibrationString != "default") {
1194 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1195 orientationCalibrationString.string());
1196 }
1197 }
1198
1199 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 String8 distanceCalibrationString;
1202 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1203 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 } else if (distanceCalibrationString != "default") {
1208 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1209 distanceCalibrationString.string());
1210 }
1211 }
1212
1213 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1214
Michael Wright227c5542020-07-02 18:30:52 +01001215 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 String8 coverageCalibrationString;
1217 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1218 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001219 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 } else if (coverageCalibrationString != "default") {
1223 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1224 coverageCalibrationString.string());
1225 }
1226 }
1227}
1228
1229void TouchInputMapper::resolveCalibration() {
1230 // Size
1231 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001232 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1233 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 }
1235 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001236 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238
1239 // Pressure
1240 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001241 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1242 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 }
1244 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001245 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247
1248 // Orientation
1249 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001250 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1251 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 }
1253 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001254 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256
1257 // Distance
1258 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001259 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1260 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 }
1262 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001263 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265
1266 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001267 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1268 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270}
1271
1272void TouchInputMapper::dumpCalibration(std::string& dump) {
1273 dump += INDENT3 "Calibration:\n";
1274
1275 // Size
1276 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001277 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 dump += INDENT4 "touch.size.calibration: none\n";
1279 break;
Michael Wright227c5542020-07-02 18:30:52 +01001280 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 dump += INDENT4 "touch.size.calibration: geometric\n";
1282 break;
Michael Wright227c5542020-07-02 18:30:52 +01001283 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 dump += INDENT4 "touch.size.calibration: diameter\n";
1285 break;
Michael Wright227c5542020-07-02 18:30:52 +01001286 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 dump += INDENT4 "touch.size.calibration: box\n";
1288 break;
Michael Wright227c5542020-07-02 18:30:52 +01001289 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 dump += INDENT4 "touch.size.calibration: area\n";
1291 break;
1292 default:
1293 ALOG_ASSERT(false);
1294 }
1295
1296 if (mCalibration.haveSizeScale) {
1297 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1298 }
1299
1300 if (mCalibration.haveSizeBias) {
1301 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1302 }
1303
1304 if (mCalibration.haveSizeIsSummed) {
1305 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1306 toString(mCalibration.sizeIsSummed));
1307 }
1308
1309 // Pressure
1310 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001311 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.pressure.calibration: none\n";
1313 break;
Michael Wright227c5542020-07-02 18:30:52 +01001314 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.pressure.calibration: physical\n";
1316 break;
Michael Wright227c5542020-07-02 18:30:52 +01001317 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1319 break;
1320 default:
1321 ALOG_ASSERT(false);
1322 }
1323
1324 if (mCalibration.havePressureScale) {
1325 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1326 }
1327
1328 // Orientation
1329 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.orientation.calibration: none\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1335 break;
Michael Wright227c5542020-07-02 18:30:52 +01001336 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 dump += INDENT4 "touch.orientation.calibration: vector\n";
1338 break;
1339 default:
1340 ALOG_ASSERT(false);
1341 }
1342
1343 // Distance
1344 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001345 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 dump += INDENT4 "touch.distance.calibration: none\n";
1347 break;
Michael Wright227c5542020-07-02 18:30:52 +01001348 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349 dump += INDENT4 "touch.distance.calibration: scaled\n";
1350 break;
1351 default:
1352 ALOG_ASSERT(false);
1353 }
1354
1355 if (mCalibration.haveDistanceScale) {
1356 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1357 }
1358
1359 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001360 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361 dump += INDENT4 "touch.coverage.calibration: none\n";
1362 break;
Michael Wright227c5542020-07-02 18:30:52 +01001363 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001364 dump += INDENT4 "touch.coverage.calibration: box\n";
1365 break;
1366 default:
1367 ALOG_ASSERT(false);
1368 }
1369}
1370
1371void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1372 dump += INDENT3 "Affine Transformation:\n";
1373
1374 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1375 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1376 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1377 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1378 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1379 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1380}
1381
1382void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001383 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001384 mSurfaceOrientation);
1385}
1386
1387void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001388 mCursorButtonAccumulator.reset(getDeviceContext());
1389 mCursorScrollAccumulator.reset(getDeviceContext());
1390 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391
1392 mPointerVelocityControl.reset();
1393 mWheelXVelocityControl.reset();
1394 mWheelYVelocityControl.reset();
1395
1396 mRawStatesPending.clear();
1397 mCurrentRawState.clear();
1398 mCurrentCookedState.clear();
1399 mLastRawState.clear();
1400 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001401 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001402 mSentHoverEnter = false;
1403 mHavePointerIds = false;
1404 mCurrentMotionAborted = false;
1405 mDownTime = 0;
1406
1407 mCurrentVirtualKey.down = false;
1408
1409 mPointerGesture.reset();
1410 mPointerSimple.reset();
1411 resetExternalStylus();
1412
1413 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001414 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001415 mPointerController->clearSpots();
1416 }
1417
1418 InputMapper::reset(when);
1419}
1420
1421void TouchInputMapper::resetExternalStylus() {
1422 mExternalStylusState.clear();
1423 mExternalStylusId = -1;
1424 mExternalStylusFusionTimeout = LLONG_MAX;
1425 mExternalStylusDataPending = false;
1426}
1427
1428void TouchInputMapper::clearStylusDataPendingFlags() {
1429 mExternalStylusDataPending = false;
1430 mExternalStylusFusionTimeout = LLONG_MAX;
1431}
1432
1433void TouchInputMapper::process(const RawEvent* rawEvent) {
1434 mCursorButtonAccumulator.process(rawEvent);
1435 mCursorScrollAccumulator.process(rawEvent);
1436 mTouchButtonAccumulator.process(rawEvent);
1437
1438 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001439 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440 }
1441}
1442
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001443void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 // Push a new state.
1445 mRawStatesPending.emplace_back();
1446
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001447 RawState& next = mRawStatesPending.back();
1448 next.clear();
1449 next.when = when;
1450 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451
1452 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001453 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001454 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1455
1456 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001457 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1458 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001459 mCursorScrollAccumulator.finishSync();
1460
1461 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001462 syncTouch(when, &next);
1463
1464 // The last RawState is the actually second to last, since we just added a new state
1465 const RawState& last =
1466 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001467
1468 // Assign pointer ids.
1469 if (!mHavePointerIds) {
1470 assignPointerIds(last, next);
1471 }
1472
1473#if DEBUG_RAW_EVENTS
1474 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001475 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001476 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1477 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1478 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1479 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001480#endif
1481
Arthur Hung9ad18942021-06-19 02:04:46 +00001482 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1483 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1484 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1485 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1486 next.rawPointerData.hoveringIdBits.value);
1487 }
1488
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001489 processRawTouches(false /*timeout*/);
1490}
1491
1492void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001493 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001494 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001495 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001496 mCurrentCookedState.clear();
1497 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498 return;
1499 }
1500
1501 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1502 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1503 // touching the current state will only observe the events that have been dispatched to the
1504 // rest of the pipeline.
1505 const size_t N = mRawStatesPending.size();
1506 size_t count;
1507 for (count = 0; count < N; count++) {
1508 const RawState& next = mRawStatesPending[count];
1509
1510 // A failure to assign the stylus id means that we're waiting on stylus data
1511 // and so should defer the rest of the pipeline.
1512 if (assignExternalStylusId(next, timeout)) {
1513 break;
1514 }
1515
1516 // All ready to go.
1517 clearStylusDataPendingFlags();
1518 mCurrentRawState.copyFrom(next);
1519 if (mCurrentRawState.when < mLastRawState.when) {
1520 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001521 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001523 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 }
1525 if (count != 0) {
1526 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1527 }
1528
1529 if (mExternalStylusDataPending) {
1530 if (timeout) {
1531 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1532 clearStylusDataPendingFlags();
1533 mCurrentRawState.copyFrom(mLastRawState);
1534#if DEBUG_STYLUS_FUSION
1535 ALOGD("Timeout expired, synthesizing event with new stylus data");
1536#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001537 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1538 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001539 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1540 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1541 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1542 }
1543 }
1544}
1545
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001546void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001547 // Always start with a clean state.
1548 mCurrentCookedState.clear();
1549
1550 // Apply stylus buttons to current raw state.
1551 applyExternalStylusButtonState(when);
1552
1553 // Handle policy on initial down or hover events.
1554 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1555 mCurrentRawState.rawPointerData.pointerCount != 0;
1556
1557 uint32_t policyFlags = 0;
1558 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1559 if (initialDown || buttonsPressed) {
1560 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001561 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001562 getContext()->fadePointer();
1563 }
1564
1565 if (mParameters.wake) {
1566 policyFlags |= POLICY_FLAG_WAKE;
1567 }
1568 }
1569
1570 // Consume raw off-screen touches before cooking pointer data.
1571 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001572 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001573 mCurrentRawState.rawPointerData.clear();
1574 }
1575
1576 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1577 // with cooked pointer data that has the same ids and indices as the raw data.
1578 // The following code can use either the raw or cooked data, as needed.
1579 cookPointerData();
1580
1581 // Apply stylus pressure to current cooked state.
1582 applyExternalStylusTouchState(when);
1583
1584 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001585 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1586 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001587 mCurrentCookedState.buttonState);
1588
1589 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001590 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1592 uint32_t id = idBits.clearFirstMarkedBit();
1593 const RawPointerData::Pointer& pointer =
1594 mCurrentRawState.rawPointerData.pointerForId(id);
1595 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1596 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1597 mCurrentCookedState.stylusIdBits.markBit(id);
1598 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1599 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1600 mCurrentCookedState.fingerIdBits.markBit(id);
1601 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1602 mCurrentCookedState.mouseIdBits.markBit(id);
1603 }
1604 }
1605 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1606 uint32_t id = idBits.clearFirstMarkedBit();
1607 const RawPointerData::Pointer& pointer =
1608 mCurrentRawState.rawPointerData.pointerForId(id);
1609 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1610 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1611 mCurrentCookedState.stylusIdBits.markBit(id);
1612 }
1613 }
1614
1615 // Stylus takes precedence over all tools, then mouse, then finger.
1616 PointerUsage pointerUsage = mPointerUsage;
1617 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1618 mCurrentCookedState.mouseIdBits.clear();
1619 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001620 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001621 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1622 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001623 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1625 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001626 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627 }
1628
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001629 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001631 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632
1633 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001634 dispatchButtonRelease(when, readTime, policyFlags);
1635 dispatchHoverExit(when, readTime, policyFlags);
1636 dispatchTouches(when, readTime, policyFlags);
1637 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1638 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001639 }
1640
1641 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1642 mCurrentMotionAborted = false;
1643 }
1644 }
1645
1646 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001647 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001648 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1649 mCurrentCookedState.buttonState);
1650
1651 // Clear some transient state.
1652 mCurrentRawState.rawVScroll = 0;
1653 mCurrentRawState.rawHScroll = 0;
1654
1655 // Copy current touch to last touch in preparation for the next cycle.
1656 mLastRawState.copyFrom(mCurrentRawState);
1657 mLastCookedState.copyFrom(mCurrentCookedState);
1658}
1659
Garfield Tanc734e4f2021-01-15 20:01:39 -08001660void TouchInputMapper::updateTouchSpots() {
1661 if (!mConfig.showTouches || mPointerController == nullptr) {
1662 return;
1663 }
1664
1665 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1666 // clear touch spots.
1667 if (mDeviceMode != DeviceMode::DIRECT &&
1668 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1669 return;
1670 }
1671
1672 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1673 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1674
1675 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001676 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1677 mCurrentCookedState.cookedPointerData.idToIndex,
1678 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001679}
1680
1681bool TouchInputMapper::isTouchScreen() {
1682 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1683 mParameters.hasAssociatedDisplay;
1684}
1685
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001686void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001687 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001688 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1689 }
1690}
1691
1692void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1693 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1694 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1695
1696 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1697 float pressure = mExternalStylusState.pressure;
1698 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1699 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1700 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1701 }
1702 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1703 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1704
1705 PointerProperties& properties =
1706 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1707 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1708 properties.toolType = mExternalStylusState.toolType;
1709 }
1710 }
1711}
1712
1713bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001714 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001715 return false;
1716 }
1717
1718 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1719 state.rawPointerData.pointerCount != 0;
1720 if (initialDown) {
1721 if (mExternalStylusState.pressure != 0.0f) {
1722#if DEBUG_STYLUS_FUSION
1723 ALOGD("Have both stylus and touch data, beginning fusion");
1724#endif
1725 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1726 } else if (timeout) {
1727#if DEBUG_STYLUS_FUSION
1728 ALOGD("Timeout expired, assuming touch is not a stylus.");
1729#endif
1730 resetExternalStylus();
1731 } else {
1732 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1733 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1734 }
1735#if DEBUG_STYLUS_FUSION
1736 ALOGD("No stylus data but stylus is connected, requesting timeout "
1737 "(%" PRId64 "ms)",
1738 mExternalStylusFusionTimeout);
1739#endif
1740 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1741 return true;
1742 }
1743 }
1744
1745 // Check if the stylus pointer has gone up.
1746 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1747#if DEBUG_STYLUS_FUSION
1748 ALOGD("Stylus pointer is going up");
1749#endif
1750 mExternalStylusId = -1;
1751 }
1752
1753 return false;
1754}
1755
1756void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001757 if (mDeviceMode == DeviceMode::POINTER) {
1758 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001759 // Since this is a synthetic event, we can consider its latency to be zero
1760 const nsecs_t readTime = when;
1761 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001762 }
Michael Wright227c5542020-07-02 18:30:52 +01001763 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001764 if (mExternalStylusFusionTimeout < when) {
1765 processRawTouches(true /*timeout*/);
1766 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1767 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1768 }
1769 }
1770}
1771
1772void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1773 mExternalStylusState.copyFrom(state);
1774 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1775 // We're either in the middle of a fused stream of data or we're waiting on data before
1776 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1777 // data.
1778 mExternalStylusDataPending = true;
1779 processRawTouches(false /*timeout*/);
1780 }
1781}
1782
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001783bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001784 // Check for release of a virtual key.
1785 if (mCurrentVirtualKey.down) {
1786 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1787 // Pointer went up while virtual key was down.
1788 mCurrentVirtualKey.down = false;
1789 if (!mCurrentVirtualKey.ignored) {
1790#if DEBUG_VIRTUAL_KEYS
1791 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1792 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1793#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001794 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001795 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1796 }
1797 return true;
1798 }
1799
1800 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1801 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1802 const RawPointerData::Pointer& pointer =
1803 mCurrentRawState.rawPointerData.pointerForId(id);
1804 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1805 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1806 // Pointer is still within the space of the virtual key.
1807 return true;
1808 }
1809 }
1810
1811 // Pointer left virtual key area or another pointer also went down.
1812 // Send key cancellation but do not consume the touch yet.
1813 // This is useful when the user swipes through from the virtual key area
1814 // into the main display surface.
1815 mCurrentVirtualKey.down = false;
1816 if (!mCurrentVirtualKey.ignored) {
1817#if DEBUG_VIRTUAL_KEYS
1818 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1819 mCurrentVirtualKey.scanCode);
1820#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001821 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001822 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1823 AKEY_EVENT_FLAG_CANCELED);
1824 }
1825 }
1826
1827 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1828 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1829 // Pointer just went down. Check for virtual key press or off-screen touches.
1830 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1831 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001832 // Exclude unscaled device for inside surface checking.
1833 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001834 // If exactly one pointer went down, check for virtual key hit.
1835 // Otherwise we will drop the entire stroke.
1836 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1837 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1838 if (virtualKey) {
1839 mCurrentVirtualKey.down = true;
1840 mCurrentVirtualKey.downTime = when;
1841 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1842 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1843 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001844 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1845 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846
1847 if (!mCurrentVirtualKey.ignored) {
1848#if DEBUG_VIRTUAL_KEYS
1849 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1850 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1851#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001852 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001853 AKEY_EVENT_FLAG_FROM_SYSTEM |
1854 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1855 }
1856 }
1857 }
1858 return true;
1859 }
1860 }
1861
1862 // Disable all virtual key touches that happen within a short time interval of the
1863 // most recent touch within the screen area. The idea is to filter out stray
1864 // virtual key presses when interacting with the touch screen.
1865 //
1866 // Problems we're trying to solve:
1867 //
1868 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1869 // virtual key area that is implemented by a separate touch panel and accidentally
1870 // triggers a virtual key.
1871 //
1872 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1873 // area and accidentally triggers a virtual key. This often happens when virtual keys
1874 // are layed out below the screen near to where the on screen keyboard's space bar
1875 // is displayed.
1876 if (mConfig.virtualKeyQuietTime > 0 &&
1877 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001878 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001879 }
1880 return false;
1881}
1882
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001883void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001884 int32_t keyEventAction, int32_t keyEventFlags) {
1885 int32_t keyCode = mCurrentVirtualKey.keyCode;
1886 int32_t scanCode = mCurrentVirtualKey.scanCode;
1887 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001888 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001889 policyFlags |= POLICY_FLAG_VIRTUAL;
1890
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001891 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1892 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1893 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001894 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001895}
1896
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001897void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001898 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1899 if (!currentIdBits.isEmpty()) {
1900 int32_t metaState = getContext()->getGlobalMetaState();
1901 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001902 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1903 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001904 mCurrentCookedState.cookedPointerData.pointerProperties,
1905 mCurrentCookedState.cookedPointerData.pointerCoords,
1906 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1907 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1908 mCurrentMotionAborted = true;
1909 }
1910}
1911
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001912void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001913 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1914 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1915 int32_t metaState = getContext()->getGlobalMetaState();
1916 int32_t buttonState = mCurrentCookedState.buttonState;
1917
1918 if (currentIdBits == lastIdBits) {
1919 if (!currentIdBits.isEmpty()) {
1920 // No pointer id changes so this is a move event.
1921 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001922 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1923 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924 mCurrentCookedState.cookedPointerData.pointerProperties,
1925 mCurrentCookedState.cookedPointerData.pointerCoords,
1926 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1927 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1928 }
1929 } else {
1930 // There may be pointers going up and pointers going down and pointers moving
1931 // all at the same time.
1932 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1933 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1934 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1935 BitSet32 dispatchedIdBits(lastIdBits.value);
1936
1937 // Update last coordinates of pointers that have moved so that we observe the new
1938 // pointer positions at the same time as other pointers that have just gone up.
1939 bool moveNeeded =
1940 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1941 mCurrentCookedState.cookedPointerData.pointerCoords,
1942 mCurrentCookedState.cookedPointerData.idToIndex,
1943 mLastCookedState.cookedPointerData.pointerProperties,
1944 mLastCookedState.cookedPointerData.pointerCoords,
1945 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1946 if (buttonState != mLastCookedState.buttonState) {
1947 moveNeeded = true;
1948 }
1949
1950 // Dispatch pointer up events.
1951 while (!upIdBits.isEmpty()) {
1952 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001953 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001954 if (isCanceled) {
1955 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1956 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001957 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001958 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001959 mLastCookedState.cookedPointerData.pointerProperties,
1960 mLastCookedState.cookedPointerData.pointerCoords,
1961 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1962 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1963 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001964 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001965 }
1966
1967 // Dispatch move events if any of the remaining pointers moved from their old locations.
1968 // Although applications receive new locations as part of individual pointer up
1969 // events, they do not generally handle them except when presented in a move event.
1970 if (moveNeeded && !moveIdBits.isEmpty()) {
1971 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001972 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1973 metaState, buttonState, 0,
1974 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001975 mCurrentCookedState.cookedPointerData.pointerCoords,
1976 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1977 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1978 }
1979
1980 // Dispatch pointer down events using the new pointer locations.
1981 while (!downIdBits.isEmpty()) {
1982 uint32_t downId = downIdBits.clearFirstMarkedBit();
1983 dispatchedIdBits.markBit(downId);
1984
1985 if (dispatchedIdBits.count() == 1) {
1986 // First pointer is going down. Set down time.
1987 mDownTime = when;
1988 }
1989
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001990 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
1991 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001992 mCurrentCookedState.cookedPointerData.pointerProperties,
1993 mCurrentCookedState.cookedPointerData.pointerCoords,
1994 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1995 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1996 }
1997 }
1998}
1999
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002000void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002001 if (mSentHoverEnter &&
2002 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2003 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2004 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002005 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2006 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002007 mLastCookedState.cookedPointerData.pointerProperties,
2008 mLastCookedState.cookedPointerData.pointerCoords,
2009 mLastCookedState.cookedPointerData.idToIndex,
2010 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2011 mOrientedYPrecision, mDownTime);
2012 mSentHoverEnter = false;
2013 }
2014}
2015
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002016void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2017 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002018 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2019 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2020 int32_t metaState = getContext()->getGlobalMetaState();
2021 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002022 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2023 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002024 mCurrentCookedState.cookedPointerData.pointerProperties,
2025 mCurrentCookedState.cookedPointerData.pointerCoords,
2026 mCurrentCookedState.cookedPointerData.idToIndex,
2027 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2028 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2029 mSentHoverEnter = true;
2030 }
2031
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002032 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2033 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002034 mCurrentCookedState.cookedPointerData.pointerProperties,
2035 mCurrentCookedState.cookedPointerData.pointerCoords,
2036 mCurrentCookedState.cookedPointerData.idToIndex,
2037 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2038 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2039 }
2040}
2041
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002042void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002043 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2044 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2045 const int32_t metaState = getContext()->getGlobalMetaState();
2046 int32_t buttonState = mLastCookedState.buttonState;
2047 while (!releasedButtons.isEmpty()) {
2048 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2049 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002050 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002051 actionButton, 0, metaState, buttonState, 0,
2052 mCurrentCookedState.cookedPointerData.pointerProperties,
2053 mCurrentCookedState.cookedPointerData.pointerCoords,
2054 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2055 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2056 }
2057}
2058
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002059void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002060 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2061 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2062 const int32_t metaState = getContext()->getGlobalMetaState();
2063 int32_t buttonState = mLastCookedState.buttonState;
2064 while (!pressedButtons.isEmpty()) {
2065 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2066 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002067 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2068 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002069 mCurrentCookedState.cookedPointerData.pointerProperties,
2070 mCurrentCookedState.cookedPointerData.pointerCoords,
2071 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2072 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2073 }
2074}
2075
2076const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2077 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2078 return cookedPointerData.touchingIdBits;
2079 }
2080 return cookedPointerData.hoveringIdBits;
2081}
2082
2083void TouchInputMapper::cookPointerData() {
2084 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2085
2086 mCurrentCookedState.cookedPointerData.clear();
2087 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2088 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2089 mCurrentRawState.rawPointerData.hoveringIdBits;
2090 mCurrentCookedState.cookedPointerData.touchingIdBits =
2091 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002092 mCurrentCookedState.cookedPointerData.canceledIdBits =
2093 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002094
2095 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2096 mCurrentCookedState.buttonState = 0;
2097 } else {
2098 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2099 }
2100
2101 // Walk through the the active pointers and map device coordinates onto
2102 // surface coordinates and adjust for display orientation.
2103 for (uint32_t i = 0; i < currentPointerCount; i++) {
2104 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2105
2106 // Size
2107 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2108 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002109 case Calibration::SizeCalibration::GEOMETRIC:
2110 case Calibration::SizeCalibration::DIAMETER:
2111 case Calibration::SizeCalibration::BOX:
2112 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2114 touchMajor = in.touchMajor;
2115 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2116 toolMajor = in.toolMajor;
2117 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2118 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2119 : in.touchMajor;
2120 } else if (mRawPointerAxes.touchMajor.valid) {
2121 toolMajor = touchMajor = in.touchMajor;
2122 toolMinor = touchMinor =
2123 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2124 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2125 : in.touchMajor;
2126 } else if (mRawPointerAxes.toolMajor.valid) {
2127 touchMajor = toolMajor = in.toolMajor;
2128 touchMinor = toolMinor =
2129 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2130 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2131 : in.toolMajor;
2132 } else {
2133 ALOG_ASSERT(false,
2134 "No touch or tool axes. "
2135 "Size calibration should have been resolved to NONE.");
2136 touchMajor = 0;
2137 touchMinor = 0;
2138 toolMajor = 0;
2139 toolMinor = 0;
2140 size = 0;
2141 }
2142
2143 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2144 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2145 if (touchingCount > 1) {
2146 touchMajor /= touchingCount;
2147 touchMinor /= touchingCount;
2148 toolMajor /= touchingCount;
2149 toolMinor /= touchingCount;
2150 size /= touchingCount;
2151 }
2152 }
2153
Michael Wright227c5542020-07-02 18:30:52 +01002154 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002155 touchMajor *= mGeometricScale;
2156 touchMinor *= mGeometricScale;
2157 toolMajor *= mGeometricScale;
2158 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002159 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002160 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2161 touchMinor = touchMajor;
2162 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2163 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002164 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165 touchMinor = touchMajor;
2166 toolMinor = toolMajor;
2167 }
2168
2169 mCalibration.applySizeScaleAndBias(&touchMajor);
2170 mCalibration.applySizeScaleAndBias(&touchMinor);
2171 mCalibration.applySizeScaleAndBias(&toolMajor);
2172 mCalibration.applySizeScaleAndBias(&toolMinor);
2173 size *= mSizeScale;
2174 break;
2175 default:
2176 touchMajor = 0;
2177 touchMinor = 0;
2178 toolMajor = 0;
2179 toolMinor = 0;
2180 size = 0;
2181 break;
2182 }
2183
2184 // Pressure
2185 float pressure;
2186 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002187 case Calibration::PressureCalibration::PHYSICAL:
2188 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002189 pressure = in.pressure * mPressureScale;
2190 break;
2191 default:
2192 pressure = in.isHovering ? 0 : 1;
2193 break;
2194 }
2195
2196 // Tilt and Orientation
2197 float tilt;
2198 float orientation;
2199 if (mHaveTilt) {
2200 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2201 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2202 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2203 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2204 } else {
2205 tilt = 0;
2206
2207 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002208 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002209 orientation = in.orientation * mOrientationScale;
2210 break;
Michael Wright227c5542020-07-02 18:30:52 +01002211 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002212 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2213 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2214 if (c1 != 0 || c2 != 0) {
2215 orientation = atan2f(c1, c2) * 0.5f;
2216 float confidence = hypotf(c1, c2);
2217 float scale = 1.0f + confidence / 16.0f;
2218 touchMajor *= scale;
2219 touchMinor /= scale;
2220 toolMajor *= scale;
2221 toolMinor /= scale;
2222 } else {
2223 orientation = 0;
2224 }
2225 break;
2226 }
2227 default:
2228 orientation = 0;
2229 }
2230 }
2231
2232 // Distance
2233 float distance;
2234 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002235 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002236 distance = in.distance * mDistanceScale;
2237 break;
2238 default:
2239 distance = 0;
2240 }
2241
2242 // Coverage
2243 int32_t rawLeft, rawTop, rawRight, rawBottom;
2244 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002245 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002246 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2247 rawRight = in.toolMinor & 0x0000ffff;
2248 rawBottom = in.toolMajor & 0x0000ffff;
2249 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2250 break;
2251 default:
2252 rawLeft = rawTop = rawRight = rawBottom = 0;
2253 break;
2254 }
2255
2256 // Adjust X,Y coords for device calibration
2257 // TODO: Adjust coverage coords?
2258 float xTransformed = in.x, yTransformed = in.y;
2259 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002260 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002261
2262 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002263 float left, top, right, bottom;
2264
2265 switch (mSurfaceOrientation) {
2266 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002267 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2268 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2269 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2270 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2271 orientation -= M_PI_2;
2272 if (mOrientedRanges.haveOrientation &&
2273 orientation < mOrientedRanges.orientation.min) {
2274 orientation +=
2275 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2276 }
2277 break;
2278 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002279 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2280 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2281 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2282 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2283 orientation -= M_PI;
2284 if (mOrientedRanges.haveOrientation &&
2285 orientation < mOrientedRanges.orientation.min) {
2286 orientation +=
2287 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2288 }
2289 break;
2290 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002291 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2292 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2293 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2294 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2295 orientation += M_PI_2;
2296 if (mOrientedRanges.haveOrientation &&
2297 orientation > mOrientedRanges.orientation.max) {
2298 orientation -=
2299 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2300 }
2301 break;
2302 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2304 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2305 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2306 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2307 break;
2308 }
2309
2310 // Write output coords.
2311 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2312 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002313 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2314 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2316 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2317 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2318 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2319 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2320 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2321 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002322 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2324 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2325 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2326 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2327 } else {
2328 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2329 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2330 }
2331
Chris Ye364fdb52020-08-05 15:07:56 -07002332 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002333 uint32_t id = in.id;
2334 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2335 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2336 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2337 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2338 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2339 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2340 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2341 }
2342
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 // Write output properties.
2344 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345 properties.clear();
2346 properties.id = id;
2347 properties.toolType = in.toolType;
2348
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002349 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002350 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002351 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 }
2353}
2354
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002355void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 PointerUsage pointerUsage) {
2357 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002358 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 mPointerUsage = pointerUsage;
2360 }
2361
2362 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002363 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002364 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 break;
Michael Wright227c5542020-07-02 18:30:52 +01002366 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002367 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 break;
Michael Wright227c5542020-07-02 18:30:52 +01002369 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002370 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 break;
Michael Wright227c5542020-07-02 18:30:52 +01002372 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 break;
2374 }
2375}
2376
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002377void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002379 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002380 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 break;
Michael Wright227c5542020-07-02 18:30:52 +01002382 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002383 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 break;
Michael Wright227c5542020-07-02 18:30:52 +01002385 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002386 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 break;
Michael Wright227c5542020-07-02 18:30:52 +01002388 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 break;
2390 }
2391
Michael Wright227c5542020-07-02 18:30:52 +01002392 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393}
2394
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002395void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2396 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 // Update current gesture coordinates.
2398 bool cancelPreviousGesture, finishPreviousGesture;
2399 bool sendEvents =
2400 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2401 if (!sendEvents) {
2402 return;
2403 }
2404 if (finishPreviousGesture) {
2405 cancelPreviousGesture = false;
2406 }
2407
2408 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002409 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002410 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 if (finishPreviousGesture || cancelPreviousGesture) {
2412 mPointerController->clearSpots();
2413 }
2414
Michael Wright227c5542020-07-02 18:30:52 +01002415 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002416 setTouchSpots(mPointerGesture.currentGestureCoords,
2417 mPointerGesture.currentGestureIdToIndex,
2418 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 }
2420 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002421 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002422 }
2423
2424 // Show or hide the pointer if needed.
2425 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002426 case PointerGesture::Mode::NEUTRAL:
2427 case PointerGesture::Mode::QUIET:
2428 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2429 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002430 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002431 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 }
2433 break;
Michael Wright227c5542020-07-02 18:30:52 +01002434 case PointerGesture::Mode::TAP:
2435 case PointerGesture::Mode::TAP_DRAG:
2436 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2437 case PointerGesture::Mode::HOVER:
2438 case PointerGesture::Mode::PRESS:
2439 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 // Unfade the pointer when the current gesture manipulates the
2441 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002442 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 break;
Michael Wright227c5542020-07-02 18:30:52 +01002444 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 // Fade the pointer when the current gesture manipulates a different
2446 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002447 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002448 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002449 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002450 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451 }
2452 break;
2453 }
2454
2455 // Send events!
2456 int32_t metaState = getContext()->getGlobalMetaState();
2457 int32_t buttonState = mCurrentCookedState.buttonState;
2458
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002459 uint32_t flags = 0;
2460
2461 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2462 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2463 }
2464
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 // Update last coordinates of pointers that have moved so that we observe the new
2466 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002467 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2468 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2469 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2470 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2471 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2472 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002473 bool moveNeeded = false;
2474 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2475 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2476 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2477 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2478 mPointerGesture.lastGestureIdBits.value);
2479 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2480 mPointerGesture.currentGestureCoords,
2481 mPointerGesture.currentGestureIdToIndex,
2482 mPointerGesture.lastGestureProperties,
2483 mPointerGesture.lastGestureCoords,
2484 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2485 if (buttonState != mLastCookedState.buttonState) {
2486 moveNeeded = true;
2487 }
2488 }
2489
2490 // Send motion events for all pointers that went up or were canceled.
2491 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2492 if (!dispatchedGestureIdBits.isEmpty()) {
2493 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002494 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2495 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2497 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2498 mPointerGesture.downTime);
2499
2500 dispatchedGestureIdBits.clear();
2501 } else {
2502 BitSet32 upGestureIdBits;
2503 if (finishPreviousGesture) {
2504 upGestureIdBits = dispatchedGestureIdBits;
2505 } else {
2506 upGestureIdBits.value =
2507 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2508 }
2509 while (!upGestureIdBits.isEmpty()) {
2510 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2511
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002512 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002513 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002514 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002515 mPointerGesture.lastGestureCoords,
2516 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2517 0, mPointerGesture.downTime);
2518
2519 dispatchedGestureIdBits.clearBit(id);
2520 }
2521 }
2522 }
2523
2524 // Send motion events for all pointers that moved.
2525 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002526 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002527 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 mPointerGesture.currentGestureProperties,
2529 mPointerGesture.currentGestureCoords,
2530 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2531 mPointerGesture.downTime);
2532 }
2533
2534 // Send motion events for all pointers that went down.
2535 if (down) {
2536 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2537 ~dispatchedGestureIdBits.value);
2538 while (!downGestureIdBits.isEmpty()) {
2539 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2540 dispatchedGestureIdBits.markBit(id);
2541
2542 if (dispatchedGestureIdBits.count() == 1) {
2543 mPointerGesture.downTime = when;
2544 }
2545
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002546 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002547 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002548 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002549 mPointerGesture.currentGestureCoords,
2550 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2551 0, mPointerGesture.downTime);
2552 }
2553 }
2554
2555 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002556 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002557 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2558 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002559 mPointerGesture.currentGestureProperties,
2560 mPointerGesture.currentGestureCoords,
2561 mPointerGesture.currentGestureIdToIndex,
2562 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2563 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2564 // Synthesize a hover move event after all pointers go up to indicate that
2565 // the pointer is hovering again even if the user is not currently touching
2566 // the touch pad. This ensures that a view will receive a fresh hover enter
2567 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002568 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002569
2570 PointerProperties pointerProperties;
2571 pointerProperties.clear();
2572 pointerProperties.id = 0;
2573 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2574
2575 PointerCoords pointerCoords;
2576 pointerCoords.clear();
2577 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2578 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2579
2580 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002581 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002582 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002583 metaState, buttonState, MotionClassification::NONE,
2584 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2585 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002586 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002587 }
2588
2589 // Update state.
2590 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2591 if (!down) {
2592 mPointerGesture.lastGestureIdBits.clear();
2593 } else {
2594 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2595 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2596 uint32_t id = idBits.clearFirstMarkedBit();
2597 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2598 mPointerGesture.lastGestureProperties[index].copyFrom(
2599 mPointerGesture.currentGestureProperties[index]);
2600 mPointerGesture.lastGestureCoords[index].copyFrom(
2601 mPointerGesture.currentGestureCoords[index]);
2602 mPointerGesture.lastGestureIdToIndex[id] = index;
2603 }
2604 }
2605}
2606
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002607void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002608 // Cancel previously dispatches pointers.
2609 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2610 int32_t metaState = getContext()->getGlobalMetaState();
2611 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002612 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2613 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002614 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2615 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2616 0, 0, mPointerGesture.downTime);
2617 }
2618
2619 // Reset the current pointer gesture.
2620 mPointerGesture.reset();
2621 mPointerVelocityControl.reset();
2622
2623 // Remove any current spots.
2624 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002625 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002626 mPointerController->clearSpots();
2627 }
2628}
2629
2630bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2631 bool* outFinishPreviousGesture, bool isTimeout) {
2632 *outCancelPreviousGesture = false;
2633 *outFinishPreviousGesture = false;
2634
2635 // Handle TAP timeout.
2636 if (isTimeout) {
2637#if DEBUG_GESTURES
2638 ALOGD("Gestures: Processing timeout");
2639#endif
2640
Michael Wright227c5542020-07-02 18:30:52 +01002641 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002642 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2643 // The tap/drag timeout has not yet expired.
2644 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2645 mConfig.pointerGestureTapDragInterval);
2646 } else {
2647 // The tap is finished.
2648#if DEBUG_GESTURES
2649 ALOGD("Gestures: TAP finished");
2650#endif
2651 *outFinishPreviousGesture = true;
2652
2653 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002654 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002655 mPointerGesture.currentGestureIdBits.clear();
2656
2657 mPointerVelocityControl.reset();
2658 return true;
2659 }
2660 }
2661
2662 // We did not handle this timeout.
2663 return false;
2664 }
2665
2666 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2667 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2668
2669 // Update the velocity tracker.
2670 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002671 std::vector<VelocityTracker::Position> positions;
2672 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002673 uint32_t id = idBits.clearFirstMarkedBit();
2674 const RawPointerData::Pointer& pointer =
2675 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002676 float x = pointer.x * mPointerXMovementScale;
2677 float y = pointer.y * mPointerYMovementScale;
2678 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002679 }
2680 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2681 positions);
2682 }
2683
2684 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2685 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002686 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2687 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2688 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002689 mPointerGesture.resetTap();
2690 }
2691
2692 // Pick a new active touch id if needed.
2693 // Choose an arbitrary pointer that just went down, if there is one.
2694 // Otherwise choose an arbitrary remaining pointer.
2695 // This guarantees we always have an active touch id when there is at least one pointer.
2696 // We keep the same active touch id for as long as possible.
2697 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2698 int32_t activeTouchId = lastActiveTouchId;
2699 if (activeTouchId < 0) {
2700 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2701 activeTouchId = mPointerGesture.activeTouchId =
2702 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2703 mPointerGesture.firstTouchTime = when;
2704 }
2705 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2706 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2707 activeTouchId = mPointerGesture.activeTouchId =
2708 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2709 } else {
2710 activeTouchId = mPointerGesture.activeTouchId = -1;
2711 }
2712 }
2713
2714 // Determine whether we are in quiet time.
2715 bool isQuietTime = false;
2716 if (activeTouchId < 0) {
2717 mPointerGesture.resetQuietTime();
2718 } else {
2719 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2720 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002721 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2722 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2723 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002724 currentFingerCount < 2) {
2725 // Enter quiet time when exiting swipe or freeform state.
2726 // This is to prevent accidentally entering the hover state and flinging the
2727 // pointer when finishing a swipe and there is still one pointer left onscreen.
2728 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002729 } else if (mPointerGesture.lastGestureMode ==
2730 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002731 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2732 // Enter quiet time when releasing the button and there are still two or more
2733 // fingers down. This may indicate that one finger was used to press the button
2734 // but it has not gone up yet.
2735 isQuietTime = true;
2736 }
2737 if (isQuietTime) {
2738 mPointerGesture.quietTime = when;
2739 }
2740 }
2741 }
2742
2743 // Switch states based on button and pointer state.
2744 if (isQuietTime) {
2745 // Case 1: Quiet time. (QUIET)
2746#if DEBUG_GESTURES
2747 ALOGD("Gestures: QUIET for next %0.3fms",
2748 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2749#endif
Michael Wright227c5542020-07-02 18:30:52 +01002750 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002751 *outFinishPreviousGesture = true;
2752 }
2753
2754 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002755 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002756 mPointerGesture.currentGestureIdBits.clear();
2757
2758 mPointerVelocityControl.reset();
2759 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2760 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2761 // The pointer follows the active touch point.
2762 // Emit DOWN, MOVE, UP events at the pointer location.
2763 //
2764 // Only the active touch matters; other fingers are ignored. This policy helps
2765 // to handle the case where the user places a second finger on the touch pad
2766 // to apply the necessary force to depress an integrated button below the surface.
2767 // We don't want the second finger to be delivered to applications.
2768 //
2769 // For this to work well, we need to make sure to track the pointer that is really
2770 // active. If the user first puts one finger down to click then adds another
2771 // finger to drag then the active pointer should switch to the finger that is
2772 // being dragged.
2773#if DEBUG_GESTURES
2774 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2775 "currentFingerCount=%d",
2776 activeTouchId, currentFingerCount);
2777#endif
2778 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002779 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002780 *outFinishPreviousGesture = true;
2781 mPointerGesture.activeGestureId = 0;
2782 }
2783
2784 // Switch pointers if needed.
2785 // Find the fastest pointer and follow it.
2786 if (activeTouchId >= 0 && currentFingerCount > 1) {
2787 int32_t bestId = -1;
2788 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2789 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2790 uint32_t id = idBits.clearFirstMarkedBit();
2791 float vx, vy;
2792 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2793 float speed = hypotf(vx, vy);
2794 if (speed > bestSpeed) {
2795 bestId = id;
2796 bestSpeed = speed;
2797 }
2798 }
2799 }
2800 if (bestId >= 0 && bestId != activeTouchId) {
2801 mPointerGesture.activeTouchId = activeTouchId = bestId;
2802#if DEBUG_GESTURES
2803 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2804 "bestId=%d, bestSpeed=%0.3f",
2805 bestId, bestSpeed);
2806#endif
2807 }
2808 }
2809
2810 float deltaX = 0, deltaY = 0;
2811 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2812 const RawPointerData::Pointer& currentPointer =
2813 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2814 const RawPointerData::Pointer& lastPointer =
2815 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2816 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2817 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2818
2819 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2820 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2821
2822 // Move the pointer using a relative motion.
2823 // When using spots, the click will occur at the position of the anchor
2824 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002825 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826 } else {
2827 mPointerVelocityControl.reset();
2828 }
2829
Prabir Pradhand7482e72021-03-09 13:54:55 -08002830 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002831
Michael Wright227c5542020-07-02 18:30:52 +01002832 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002833 mPointerGesture.currentGestureIdBits.clear();
2834 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2835 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2836 mPointerGesture.currentGestureProperties[0].clear();
2837 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2838 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2839 mPointerGesture.currentGestureCoords[0].clear();
2840 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2841 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2842 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2843 } else if (currentFingerCount == 0) {
2844 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002845 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002846 *outFinishPreviousGesture = true;
2847 }
2848
2849 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2850 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2851 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002852 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2853 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 lastFingerCount == 1) {
2855 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002856 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2858 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2859#if DEBUG_GESTURES
2860 ALOGD("Gestures: TAP");
2861#endif
2862
2863 mPointerGesture.tapUpTime = when;
2864 getContext()->requestTimeoutAtTime(when +
2865 mConfig.pointerGestureTapDragInterval);
2866
2867 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002868 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869 mPointerGesture.currentGestureIdBits.clear();
2870 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2871 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2872 mPointerGesture.currentGestureProperties[0].clear();
2873 mPointerGesture.currentGestureProperties[0].id =
2874 mPointerGesture.activeGestureId;
2875 mPointerGesture.currentGestureProperties[0].toolType =
2876 AMOTION_EVENT_TOOL_TYPE_FINGER;
2877 mPointerGesture.currentGestureCoords[0].clear();
2878 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2879 mPointerGesture.tapX);
2880 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2881 mPointerGesture.tapY);
2882 mPointerGesture.currentGestureCoords[0]
2883 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2884
2885 tapped = true;
2886 } else {
2887#if DEBUG_GESTURES
2888 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2889 y - mPointerGesture.tapY);
2890#endif
2891 }
2892 } else {
2893#if DEBUG_GESTURES
2894 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2895 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2896 (when - mPointerGesture.tapDownTime) * 0.000001f);
2897 } else {
2898 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2899 }
2900#endif
2901 }
2902 }
2903
2904 mPointerVelocityControl.reset();
2905
2906 if (!tapped) {
2907#if DEBUG_GESTURES
2908 ALOGD("Gestures: NEUTRAL");
2909#endif
2910 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002911 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002912 mPointerGesture.currentGestureIdBits.clear();
2913 }
2914 } else if (currentFingerCount == 1) {
2915 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2916 // The pointer follows the active touch point.
2917 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2918 // When in TAP_DRAG, emit MOVE events at the pointer location.
2919 ALOG_ASSERT(activeTouchId >= 0);
2920
Michael Wright227c5542020-07-02 18:30:52 +01002921 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2922 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002923 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002924 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002925 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2926 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002927 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002928 } else {
2929#if DEBUG_GESTURES
2930 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2931 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2932#endif
2933 }
2934 } else {
2935#if DEBUG_GESTURES
2936 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2937 (when - mPointerGesture.tapUpTime) * 0.000001f);
2938#endif
2939 }
Michael Wright227c5542020-07-02 18:30:52 +01002940 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2941 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002942 }
2943
2944 float deltaX = 0, deltaY = 0;
2945 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2946 const RawPointerData::Pointer& currentPointer =
2947 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2948 const RawPointerData::Pointer& lastPointer =
2949 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2950 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2951 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2952
2953 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2954 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2955
2956 // Move the pointer using a relative motion.
2957 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002958 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002959 } else {
2960 mPointerVelocityControl.reset();
2961 }
2962
2963 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002964 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002965#if DEBUG_GESTURES
2966 ALOGD("Gestures: TAP_DRAG");
2967#endif
2968 down = true;
2969 } else {
2970#if DEBUG_GESTURES
2971 ALOGD("Gestures: HOVER");
2972#endif
Michael Wright227c5542020-07-02 18:30:52 +01002973 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974 *outFinishPreviousGesture = true;
2975 }
2976 mPointerGesture.activeGestureId = 0;
2977 down = false;
2978 }
2979
Prabir Pradhand7482e72021-03-09 13:54:55 -08002980 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981
2982 mPointerGesture.currentGestureIdBits.clear();
2983 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2984 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2985 mPointerGesture.currentGestureProperties[0].clear();
2986 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2987 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2988 mPointerGesture.currentGestureCoords[0].clear();
2989 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2990 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2991 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2992 down ? 1.0f : 0.0f);
2993
2994 if (lastFingerCount == 0 && currentFingerCount != 0) {
2995 mPointerGesture.resetTap();
2996 mPointerGesture.tapDownTime = when;
2997 mPointerGesture.tapX = x;
2998 mPointerGesture.tapY = y;
2999 }
3000 } else {
3001 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3002 // We need to provide feedback for each finger that goes down so we cannot wait
3003 // for the fingers to move before deciding what to do.
3004 //
3005 // The ambiguous case is deciding what to do when there are two fingers down but they
3006 // have not moved enough to determine whether they are part of a drag or part of a
3007 // freeform gesture, or just a press or long-press at the pointer location.
3008 //
3009 // When there are two fingers we start with the PRESS hypothesis and we generate a
3010 // down at the pointer location.
3011 //
3012 // When the two fingers move enough or when additional fingers are added, we make
3013 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3014 ALOG_ASSERT(activeTouchId >= 0);
3015
3016 bool settled = when >=
3017 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003018 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3019 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3020 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003021 *outFinishPreviousGesture = true;
3022 } else if (!settled && currentFingerCount > lastFingerCount) {
3023 // Additional pointers have gone down but not yet settled.
3024 // Reset the gesture.
3025#if DEBUG_GESTURES
3026 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3027 "settle time remaining %0.3fms",
3028 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3029 when) * 0.000001f);
3030#endif
3031 *outCancelPreviousGesture = true;
3032 } else {
3033 // Continue previous gesture.
3034 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3035 }
3036
3037 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003038 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003039 mPointerGesture.activeGestureId = 0;
3040 mPointerGesture.referenceIdBits.clear();
3041 mPointerVelocityControl.reset();
3042
3043 // Use the centroid and pointer location as the reference points for the gesture.
3044#if DEBUG_GESTURES
3045 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3046 "settle time remaining %0.3fms",
3047 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3048 when) * 0.000001f);
3049#endif
3050 mCurrentRawState.rawPointerData
3051 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3052 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003053 auto [x, y] = getMouseCursorPosition();
3054 mPointerGesture.referenceGestureX = x;
3055 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003056 }
3057
3058 // Clear the reference deltas for fingers not yet included in the reference calculation.
3059 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3060 ~mPointerGesture.referenceIdBits.value);
3061 !idBits.isEmpty();) {
3062 uint32_t id = idBits.clearFirstMarkedBit();
3063 mPointerGesture.referenceDeltas[id].dx = 0;
3064 mPointerGesture.referenceDeltas[id].dy = 0;
3065 }
3066 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3067
3068 // Add delta for all fingers and calculate a common movement delta.
3069 float commonDeltaX = 0, commonDeltaY = 0;
3070 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3071 mCurrentCookedState.fingerIdBits.value);
3072 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3073 bool first = (idBits == commonIdBits);
3074 uint32_t id = idBits.clearFirstMarkedBit();
3075 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3076 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3077 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3078 delta.dx += cpd.x - lpd.x;
3079 delta.dy += cpd.y - lpd.y;
3080
3081 if (first) {
3082 commonDeltaX = delta.dx;
3083 commonDeltaY = delta.dy;
3084 } else {
3085 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3086 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3087 }
3088 }
3089
3090 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003091 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003092 float dist[MAX_POINTER_ID + 1];
3093 int32_t distOverThreshold = 0;
3094 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3095 uint32_t id = idBits.clearFirstMarkedBit();
3096 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3097 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3098 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3099 distOverThreshold += 1;
3100 }
3101 }
3102
3103 // Only transition when at least two pointers have moved further than
3104 // the minimum distance threshold.
3105 if (distOverThreshold >= 2) {
3106 if (currentFingerCount > 2) {
3107 // There are more than two pointers, switch to FREEFORM.
3108#if DEBUG_GESTURES
3109 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3110 currentFingerCount);
3111#endif
3112 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003113 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003114 } else {
3115 // There are exactly two pointers.
3116 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3117 uint32_t id1 = idBits.clearFirstMarkedBit();
3118 uint32_t id2 = idBits.firstMarkedBit();
3119 const RawPointerData::Pointer& p1 =
3120 mCurrentRawState.rawPointerData.pointerForId(id1);
3121 const RawPointerData::Pointer& p2 =
3122 mCurrentRawState.rawPointerData.pointerForId(id2);
3123 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3124 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3125 // There are two pointers but they are too far apart for a SWIPE,
3126 // switch to FREEFORM.
3127#if DEBUG_GESTURES
3128 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3129 mutualDistance, mPointerGestureMaxSwipeWidth);
3130#endif
3131 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003132 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003133 } else {
3134 // There are two pointers. Wait for both pointers to start moving
3135 // before deciding whether this is a SWIPE or FREEFORM gesture.
3136 float dist1 = dist[id1];
3137 float dist2 = dist[id2];
3138 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3139 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3140 // Calculate the dot product of the displacement vectors.
3141 // When the vectors are oriented in approximately the same direction,
3142 // the angle betweeen them is near zero and the cosine of the angle
3143 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3144 // mag(v2).
3145 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3146 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3147 float dx1 = delta1.dx * mPointerXZoomScale;
3148 float dy1 = delta1.dy * mPointerYZoomScale;
3149 float dx2 = delta2.dx * mPointerXZoomScale;
3150 float dy2 = delta2.dy * mPointerYZoomScale;
3151 float dot = dx1 * dx2 + dy1 * dy2;
3152 float cosine = dot / (dist1 * dist2); // denominator always > 0
3153 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3154 // Pointers are moving in the same direction. Switch to SWIPE.
3155#if DEBUG_GESTURES
3156 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3157 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3158 "cosine %0.3f >= %0.3f",
3159 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3160 mConfig.pointerGestureMultitouchMinDistance, cosine,
3161 mConfig.pointerGestureSwipeTransitionAngleCosine);
3162#endif
Michael Wright227c5542020-07-02 18:30:52 +01003163 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003164 } else {
3165 // Pointers are moving in different directions. Switch to FREEFORM.
3166#if DEBUG_GESTURES
3167 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3168 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3169 "cosine %0.3f < %0.3f",
3170 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3171 mConfig.pointerGestureMultitouchMinDistance, cosine,
3172 mConfig.pointerGestureSwipeTransitionAngleCosine);
3173#endif
3174 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003175 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003176 }
3177 }
3178 }
3179 }
3180 }
Michael Wright227c5542020-07-02 18:30:52 +01003181 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003182 // Switch from SWIPE to FREEFORM if additional pointers go down.
3183 // Cancel previous gesture.
3184 if (currentFingerCount > 2) {
3185#if DEBUG_GESTURES
3186 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3187 currentFingerCount);
3188#endif
3189 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003190 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003191 }
3192 }
3193
3194 // Move the reference points based on the overall group motion of the fingers
3195 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003196 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003197 (commonDeltaX || commonDeltaY)) {
3198 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3199 uint32_t id = idBits.clearFirstMarkedBit();
3200 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3201 delta.dx = 0;
3202 delta.dy = 0;
3203 }
3204
3205 mPointerGesture.referenceTouchX += commonDeltaX;
3206 mPointerGesture.referenceTouchY += commonDeltaY;
3207
3208 commonDeltaX *= mPointerXMovementScale;
3209 commonDeltaY *= mPointerYMovementScale;
3210
3211 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3212 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3213
3214 mPointerGesture.referenceGestureX += commonDeltaX;
3215 mPointerGesture.referenceGestureY += commonDeltaY;
3216 }
3217
3218 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003219 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3220 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003221 // PRESS or SWIPE mode.
3222#if DEBUG_GESTURES
3223 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3224 "activeGestureId=%d, currentTouchPointerCount=%d",
3225 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3226#endif
3227 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3228
3229 mPointerGesture.currentGestureIdBits.clear();
3230 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3231 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3232 mPointerGesture.currentGestureProperties[0].clear();
3233 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3234 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3235 mPointerGesture.currentGestureCoords[0].clear();
3236 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3237 mPointerGesture.referenceGestureX);
3238 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3239 mPointerGesture.referenceGestureY);
3240 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003241 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003242 // FREEFORM mode.
3243#if DEBUG_GESTURES
3244 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3245 "activeGestureId=%d, currentTouchPointerCount=%d",
3246 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3247#endif
3248 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3249
3250 mPointerGesture.currentGestureIdBits.clear();
3251
3252 BitSet32 mappedTouchIdBits;
3253 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003254 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003255 // Initially, assign the active gesture id to the active touch point
3256 // if there is one. No other touch id bits are mapped yet.
3257 if (!*outCancelPreviousGesture) {
3258 mappedTouchIdBits.markBit(activeTouchId);
3259 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3260 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3261 mPointerGesture.activeGestureId;
3262 } else {
3263 mPointerGesture.activeGestureId = -1;
3264 }
3265 } else {
3266 // Otherwise, assume we mapped all touches from the previous frame.
3267 // Reuse all mappings that are still applicable.
3268 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3269 mCurrentCookedState.fingerIdBits.value;
3270 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3271
3272 // Check whether we need to choose a new active gesture id because the
3273 // current went went up.
3274 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3275 ~mCurrentCookedState.fingerIdBits.value);
3276 !upTouchIdBits.isEmpty();) {
3277 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3278 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3279 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3280 mPointerGesture.activeGestureId = -1;
3281 break;
3282 }
3283 }
3284 }
3285
3286#if DEBUG_GESTURES
3287 ALOGD("Gestures: FREEFORM follow up "
3288 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3289 "activeGestureId=%d",
3290 mappedTouchIdBits.value, usedGestureIdBits.value,
3291 mPointerGesture.activeGestureId);
3292#endif
3293
3294 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3295 for (uint32_t i = 0; i < currentFingerCount; i++) {
3296 uint32_t touchId = idBits.clearFirstMarkedBit();
3297 uint32_t gestureId;
3298 if (!mappedTouchIdBits.hasBit(touchId)) {
3299 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3300 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3301#if DEBUG_GESTURES
3302 ALOGD("Gestures: FREEFORM "
3303 "new mapping for touch id %d -> gesture id %d",
3304 touchId, gestureId);
3305#endif
3306 } else {
3307 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3308#if DEBUG_GESTURES
3309 ALOGD("Gestures: FREEFORM "
3310 "existing mapping for touch id %d -> gesture id %d",
3311 touchId, gestureId);
3312#endif
3313 }
3314 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3315 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3316
3317 const RawPointerData::Pointer& pointer =
3318 mCurrentRawState.rawPointerData.pointerForId(touchId);
3319 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3320 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3321 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3322
3323 mPointerGesture.currentGestureProperties[i].clear();
3324 mPointerGesture.currentGestureProperties[i].id = gestureId;
3325 mPointerGesture.currentGestureProperties[i].toolType =
3326 AMOTION_EVENT_TOOL_TYPE_FINGER;
3327 mPointerGesture.currentGestureCoords[i].clear();
3328 mPointerGesture.currentGestureCoords[i]
3329 .setAxisValue(AMOTION_EVENT_AXIS_X,
3330 mPointerGesture.referenceGestureX + deltaX);
3331 mPointerGesture.currentGestureCoords[i]
3332 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3333 mPointerGesture.referenceGestureY + deltaY);
3334 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3335 1.0f);
3336 }
3337
3338 if (mPointerGesture.activeGestureId < 0) {
3339 mPointerGesture.activeGestureId =
3340 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3341#if DEBUG_GESTURES
3342 ALOGD("Gestures: FREEFORM new "
3343 "activeGestureId=%d",
3344 mPointerGesture.activeGestureId);
3345#endif
3346 }
3347 }
3348 }
3349
3350 mPointerController->setButtonState(mCurrentRawState.buttonState);
3351
3352#if DEBUG_GESTURES
3353 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3354 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3355 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3356 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3357 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3358 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3359 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3360 uint32_t id = idBits.clearFirstMarkedBit();
3361 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3362 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3363 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3364 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3365 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3366 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3367 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3368 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3369 }
3370 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3371 uint32_t id = idBits.clearFirstMarkedBit();
3372 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3373 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3374 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3375 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3376 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3377 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3378 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3379 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3380 }
3381#endif
3382 return true;
3383}
3384
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003385void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003386 mPointerSimple.currentCoords.clear();
3387 mPointerSimple.currentProperties.clear();
3388
3389 bool down, hovering;
3390 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3391 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3392 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003393 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3394 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003395
3396 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3397 down = !hovering;
3398
Prabir Pradhand7482e72021-03-09 13:54:55 -08003399 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003400 mPointerSimple.currentCoords.copyFrom(
3401 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3402 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3403 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3404 mPointerSimple.currentProperties.id = 0;
3405 mPointerSimple.currentProperties.toolType =
3406 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3407 } else {
3408 down = false;
3409 hovering = false;
3410 }
3411
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003412 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003413}
3414
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003415void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3416 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003417}
3418
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003419void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003420 mPointerSimple.currentCoords.clear();
3421 mPointerSimple.currentProperties.clear();
3422
3423 bool down, hovering;
3424 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3425 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3426 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3427 float deltaX = 0, deltaY = 0;
3428 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3429 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3430 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3431 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3432 mPointerXMovementScale;
3433 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3434 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3435 mPointerYMovementScale;
3436
3437 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3438 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3439
Prabir Pradhand7482e72021-03-09 13:54:55 -08003440 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003441 } else {
3442 mPointerVelocityControl.reset();
3443 }
3444
3445 down = isPointerDown(mCurrentRawState.buttonState);
3446 hovering = !down;
3447
Prabir Pradhand7482e72021-03-09 13:54:55 -08003448 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003449 mPointerSimple.currentCoords.copyFrom(
3450 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3451 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3452 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3453 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3454 hovering ? 0.0f : 1.0f);
3455 mPointerSimple.currentProperties.id = 0;
3456 mPointerSimple.currentProperties.toolType =
3457 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3458 } else {
3459 mPointerVelocityControl.reset();
3460
3461 down = false;
3462 hovering = false;
3463 }
3464
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003465 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003466}
3467
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003468void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3469 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003470
3471 mPointerVelocityControl.reset();
3472}
3473
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003474void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3475 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003476 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003477
3478 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003479 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003480 mPointerController->clearSpots();
3481 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003482 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003483 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003484 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003485 }
Garfield Tan9514d782020-11-10 16:37:23 -08003486 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003487
Prabir Pradhand7482e72021-03-09 13:54:55 -08003488 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489
3490 if (mPointerSimple.down && !down) {
3491 mPointerSimple.down = false;
3492
3493 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003494 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3495 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003496 mLastRawState.buttonState, MotionClassification::NONE,
3497 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3498 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3499 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3500 /* videoFrames */ {});
3501 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003502 }
3503
3504 if (mPointerSimple.hovering && !hovering) {
3505 mPointerSimple.hovering = false;
3506
3507 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003508 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3509 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3510 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003511 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3512 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3513 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3514 /* videoFrames */ {});
3515 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003516 }
3517
3518 if (down) {
3519 if (!mPointerSimple.down) {
3520 mPointerSimple.down = true;
3521 mPointerSimple.downTime = when;
3522
3523 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003524 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003525 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3526 metaState, mCurrentRawState.buttonState,
3527 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3528 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3529 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3530 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3531 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003532 }
3533
3534 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003535 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3536 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003537 mCurrentRawState.buttonState, MotionClassification::NONE,
3538 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3539 &mPointerSimple.currentCoords, mOrientedXPrecision,
3540 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3541 mPointerSimple.downTime, /* videoFrames */ {});
3542 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003543 }
3544
3545 if (hovering) {
3546 if (!mPointerSimple.hovering) {
3547 mPointerSimple.hovering = true;
3548
3549 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003550 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003551 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3552 metaState, mCurrentRawState.buttonState,
3553 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3554 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3555 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3556 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3557 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003558 }
3559
3560 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003561 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3562 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3563 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003564 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3565 &mPointerSimple.currentCoords, mOrientedXPrecision,
3566 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3567 mPointerSimple.downTime, /* videoFrames */ {});
3568 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003569 }
3570
3571 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3572 float vscroll = mCurrentRawState.rawVScroll;
3573 float hscroll = mCurrentRawState.rawHScroll;
3574 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3575 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3576
3577 // Send scroll.
3578 PointerCoords pointerCoords;
3579 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3580 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3581 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3582
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003583 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3584 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003585 mCurrentRawState.buttonState, MotionClassification::NONE,
3586 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3587 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3588 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3589 /* videoFrames */ {});
3590 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003591 }
3592
3593 // Save state.
3594 if (down || hovering) {
3595 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3596 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3597 } else {
3598 mPointerSimple.reset();
3599 }
3600}
3601
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003602void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003603 mPointerSimple.currentCoords.clear();
3604 mPointerSimple.currentProperties.clear();
3605
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003606 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003607}
3608
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003609void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3610 uint32_t source, int32_t action, int32_t actionButton,
3611 int32_t flags, int32_t metaState, int32_t buttonState,
3612 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003613 const PointerCoords* coords, const uint32_t* idToIndex,
3614 BitSet32 idBits, int32_t changedId, float xPrecision,
3615 float yPrecision, nsecs_t downTime) {
3616 PointerCoords pointerCoords[MAX_POINTERS];
3617 PointerProperties pointerProperties[MAX_POINTERS];
3618 uint32_t pointerCount = 0;
3619 while (!idBits.isEmpty()) {
3620 uint32_t id = idBits.clearFirstMarkedBit();
3621 uint32_t index = idToIndex[id];
3622 pointerProperties[pointerCount].copyFrom(properties[index]);
3623 pointerCoords[pointerCount].copyFrom(coords[index]);
3624
3625 if (changedId >= 0 && id == uint32_t(changedId)) {
3626 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3627 }
3628
3629 pointerCount += 1;
3630 }
3631
3632 ALOG_ASSERT(pointerCount != 0);
3633
3634 if (changedId >= 0 && pointerCount == 1) {
3635 // Replace initial down and final up action.
3636 // We can compare the action without masking off the changed pointer index
3637 // because we know the index is 0.
3638 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3639 action = AMOTION_EVENT_ACTION_DOWN;
3640 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003641 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3642 action = AMOTION_EVENT_ACTION_CANCEL;
3643 } else {
3644 action = AMOTION_EVENT_ACTION_UP;
3645 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003646 } else {
3647 // Can't happen.
3648 ALOG_ASSERT(false);
3649 }
3650 }
3651 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3652 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003653 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003654 auto [x, y] = getMouseCursorPosition();
3655 xCursorPosition = x;
3656 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003657 }
3658 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3659 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003660 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003661 std::for_each(frames.begin(), frames.end(),
3662 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003663 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3664 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003665 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3666 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3667 downTime, std::move(frames));
3668 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003669}
3670
3671bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3672 const PointerCoords* inCoords,
3673 const uint32_t* inIdToIndex,
3674 PointerProperties* outProperties,
3675 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3676 BitSet32 idBits) const {
3677 bool changed = false;
3678 while (!idBits.isEmpty()) {
3679 uint32_t id = idBits.clearFirstMarkedBit();
3680 uint32_t inIndex = inIdToIndex[id];
3681 uint32_t outIndex = outIdToIndex[id];
3682
3683 const PointerProperties& curInProperties = inProperties[inIndex];
3684 const PointerCoords& curInCoords = inCoords[inIndex];
3685 PointerProperties& curOutProperties = outProperties[outIndex];
3686 PointerCoords& curOutCoords = outCoords[outIndex];
3687
3688 if (curInProperties != curOutProperties) {
3689 curOutProperties.copyFrom(curInProperties);
3690 changed = true;
3691 }
3692
3693 if (curInCoords != curOutCoords) {
3694 curOutCoords.copyFrom(curInCoords);
3695 changed = true;
3696 }
3697 }
3698 return changed;
3699}
3700
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003701void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3702 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3703 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003704}
3705
Arthur Hung4197f6b2020-03-16 15:39:59 +08003706// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003707void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003708 // Scale to surface coordinate.
3709 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3710 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3711
arthurhunga36b28e2020-12-29 20:28:15 +08003712 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3713 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3714
Arthur Hung4197f6b2020-03-16 15:39:59 +08003715 // Rotate to surface coordinate.
3716 // 0 - no swap and reverse.
3717 // 90 - swap x/y and reverse y.
3718 // 180 - reverse x, y.
3719 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003720 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003721 case DISPLAY_ORIENTATION_0:
3722 x = xScaled + mXTranslate;
3723 y = yScaled + mYTranslate;
3724 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003725 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003726 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003727 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003728 break;
3729 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003730 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3731 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003732 break;
3733 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003734 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003735 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003736 break;
3737 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003738 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003739 }
3740}
3741
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003742bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003743 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3744 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3745
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003746 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003747 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003748 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003749 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003750}
3751
3752const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3753 for (const VirtualKey& virtualKey : mVirtualKeys) {
3754#if DEBUG_VIRTUAL_KEYS
3755 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3756 "left=%d, top=%d, right=%d, bottom=%d",
3757 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3758 virtualKey.hitRight, virtualKey.hitBottom);
3759#endif
3760
3761 if (virtualKey.isHit(x, y)) {
3762 return &virtualKey;
3763 }
3764 }
3765
3766 return nullptr;
3767}
3768
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003769void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3770 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3771 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003772
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003773 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003774
3775 if (currentPointerCount == 0) {
3776 // No pointers to assign.
3777 return;
3778 }
3779
3780 if (lastPointerCount == 0) {
3781 // All pointers are new.
3782 for (uint32_t i = 0; i < currentPointerCount; i++) {
3783 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003784 current.rawPointerData.pointers[i].id = id;
3785 current.rawPointerData.idToIndex[id] = i;
3786 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003787 }
3788 return;
3789 }
3790
3791 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003792 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003793 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003794 uint32_t id = last.rawPointerData.pointers[0].id;
3795 current.rawPointerData.pointers[0].id = id;
3796 current.rawPointerData.idToIndex[id] = 0;
3797 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003798 return;
3799 }
3800
3801 // General case.
3802 // We build a heap of squared euclidean distances between current and last pointers
3803 // associated with the current and last pointer indices. Then, we find the best
3804 // match (by distance) for each current pointer.
3805 // The pointers must have the same tool type but it is possible for them to
3806 // transition from hovering to touching or vice-versa while retaining the same id.
3807 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3808
3809 uint32_t heapSize = 0;
3810 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3811 currentPointerIndex++) {
3812 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3813 lastPointerIndex++) {
3814 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003815 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003816 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003817 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003818 if (currentPointer.toolType == lastPointer.toolType) {
3819 int64_t deltaX = currentPointer.x - lastPointer.x;
3820 int64_t deltaY = currentPointer.y - lastPointer.y;
3821
3822 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3823
3824 // Insert new element into the heap (sift up).
3825 heap[heapSize].currentPointerIndex = currentPointerIndex;
3826 heap[heapSize].lastPointerIndex = lastPointerIndex;
3827 heap[heapSize].distance = distance;
3828 heapSize += 1;
3829 }
3830 }
3831 }
3832
3833 // Heapify
3834 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3835 startIndex -= 1;
3836 for (uint32_t parentIndex = startIndex;;) {
3837 uint32_t childIndex = parentIndex * 2 + 1;
3838 if (childIndex >= heapSize) {
3839 break;
3840 }
3841
3842 if (childIndex + 1 < heapSize &&
3843 heap[childIndex + 1].distance < heap[childIndex].distance) {
3844 childIndex += 1;
3845 }
3846
3847 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3848 break;
3849 }
3850
3851 swap(heap[parentIndex], heap[childIndex]);
3852 parentIndex = childIndex;
3853 }
3854 }
3855
3856#if DEBUG_POINTER_ASSIGNMENT
3857 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3858 for (size_t i = 0; i < heapSize; i++) {
3859 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3860 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3861 }
3862#endif
3863
3864 // Pull matches out by increasing order of distance.
3865 // To avoid reassigning pointers that have already been matched, the loop keeps track
3866 // of which last and current pointers have been matched using the matchedXXXBits variables.
3867 // It also tracks the used pointer id bits.
3868 BitSet32 matchedLastBits(0);
3869 BitSet32 matchedCurrentBits(0);
3870 BitSet32 usedIdBits(0);
3871 bool first = true;
3872 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3873 while (heapSize > 0) {
3874 if (first) {
3875 // The first time through the loop, we just consume the root element of
3876 // the heap (the one with smallest distance).
3877 first = false;
3878 } else {
3879 // Previous iterations consumed the root element of the heap.
3880 // Pop root element off of the heap (sift down).
3881 heap[0] = heap[heapSize];
3882 for (uint32_t parentIndex = 0;;) {
3883 uint32_t childIndex = parentIndex * 2 + 1;
3884 if (childIndex >= heapSize) {
3885 break;
3886 }
3887
3888 if (childIndex + 1 < heapSize &&
3889 heap[childIndex + 1].distance < heap[childIndex].distance) {
3890 childIndex += 1;
3891 }
3892
3893 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3894 break;
3895 }
3896
3897 swap(heap[parentIndex], heap[childIndex]);
3898 parentIndex = childIndex;
3899 }
3900
3901#if DEBUG_POINTER_ASSIGNMENT
3902 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003903 for (size_t j = 0; j < heapSize; j++) {
3904 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3905 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003906 }
3907#endif
3908 }
3909
3910 heapSize -= 1;
3911
3912 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3913 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3914
3915 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3916 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3917
3918 matchedCurrentBits.markBit(currentPointerIndex);
3919 matchedLastBits.markBit(lastPointerIndex);
3920
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003921 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3922 current.rawPointerData.pointers[currentPointerIndex].id = id;
3923 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3924 current.rawPointerData.markIdBit(id,
3925 current.rawPointerData.isHovering(
3926 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003927 usedIdBits.markBit(id);
3928
3929#if DEBUG_POINTER_ASSIGNMENT
3930 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3931 ", distance=%" PRIu64,
3932 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3933#endif
3934 break;
3935 }
3936 }
3937
3938 // Assign fresh ids to pointers that were not matched in the process.
3939 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3940 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3941 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3942
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003943 current.rawPointerData.pointers[currentPointerIndex].id = id;
3944 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3945 current.rawPointerData.markIdBit(id,
3946 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003947
3948#if DEBUG_POINTER_ASSIGNMENT
3949 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3950#endif
3951 }
3952}
3953
3954int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3955 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3956 return AKEY_STATE_VIRTUAL;
3957 }
3958
3959 for (const VirtualKey& virtualKey : mVirtualKeys) {
3960 if (virtualKey.keyCode == keyCode) {
3961 return AKEY_STATE_UP;
3962 }
3963 }
3964
3965 return AKEY_STATE_UNKNOWN;
3966}
3967
3968int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3969 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3970 return AKEY_STATE_VIRTUAL;
3971 }
3972
3973 for (const VirtualKey& virtualKey : mVirtualKeys) {
3974 if (virtualKey.scanCode == scanCode) {
3975 return AKEY_STATE_UP;
3976 }
3977 }
3978
3979 return AKEY_STATE_UNKNOWN;
3980}
3981
3982bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3983 const int32_t* keyCodes, uint8_t* outFlags) {
3984 for (const VirtualKey& virtualKey : mVirtualKeys) {
3985 for (size_t i = 0; i < numCodes; i++) {
3986 if (virtualKey.keyCode == keyCodes[i]) {
3987 outFlags[i] = 1;
3988 }
3989 }
3990 }
3991
3992 return true;
3993}
3994
3995std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3996 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003997 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003998 return std::make_optional(mPointerController->getDisplayId());
3999 } else {
4000 return std::make_optional(mViewport.displayId);
4001 }
4002 }
4003 return std::nullopt;
4004}
4005
Prabir Pradhand7482e72021-03-09 13:54:55 -08004006void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
4007 if (isPerWindowInputRotationEnabled()) {
4008 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4009 // space that is oriented with the viewport.
4010 rotateDelta(mViewport.orientation, &dx, &dy);
4011 }
4012
4013 mPointerController->move(dx, dy);
4014}
4015
4016std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4017 float x = 0;
4018 float y = 0;
4019 mPointerController->getPosition(&x, &y);
4020
4021 if (!isPerWindowInputRotationEnabled()) return {x, y};
4022 if (!mViewport.isValid()) return {x, y};
4023
4024 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4025 // to InputReader's un-rotated coordinate space.
4026 const int32_t orientation = getInverseRotation(mViewport.orientation);
4027 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4028 return {x, y};
4029}
4030
4031void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4032 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4033 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4034 // coordinate space that is oriented with the viewport.
4035 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4036 }
4037
4038 mPointerController->setPosition(x, y);
4039}
4040
4041void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4042 BitSet32 spotIdBits, int32_t displayId) {
4043 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4044
4045 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4046 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4047 float x = spotCoords[index].getX();
4048 float y = spotCoords[index].getY();
4049 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4050
4051 if (isPerWindowInputRotationEnabled()) {
4052 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4053 // coordinate space.
4054 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4055 }
4056
4057 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4058 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4059 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4060 }
4061
4062 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4063}
4064
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004065} // namespace android