blob: 09e1c05ae93d28d755b0e5565403641c2765f9c8 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
Chris Yea03dd232020-09-08 19:21:09 -070021#include <input/NamedEnum.h>
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070022#include "TouchInputMapper.h"
23
24#include "CursorButtonAccumulator.h"
25#include "CursorScrollAccumulator.h"
26#include "TouchButtonAccumulator.h"
27#include "TouchCursorInputMapperCommon.h"
28
29namespace android {
30
Prabir Pradhand7482e72021-03-09 13:54:55 -080031namespace {
32
33// Rotates the given point (x, y) by the supplied orientation. The width and height are the
34// dimensions of the surface prior to this rotation being applied.
35void rotatePoint(int32_t orientation, float& x, float& y, int32_t width, int32_t height) {
36 rotateDelta(orientation, &x, &y);
37 switch (orientation) {
38 case DISPLAY_ORIENTATION_90:
39 y += width;
40 break;
41 case DISPLAY_ORIENTATION_180:
42 x += width;
43 y += height;
44 break;
45 case DISPLAY_ORIENTATION_270:
46 x += height;
47 break;
48 default:
49 break;
50 }
51}
52
53} // namespace
54
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070055// --- Constants ---
56
57// Maximum amount of latency to add to touch events while waiting for data from an
58// external stylus.
59static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
60
61// Maximum amount of time to wait on touch data before pushing out new pressure data.
62static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
63
64// Artificial latency on synthetic events created from stylus data without corresponding touch
65// data.
66static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
67
68// --- Static Definitions ---
69
70template <typename T>
71inline static void swap(T& a, T& b) {
72 T temp = a;
73 a = b;
74 b = temp;
75}
76
77static float calculateCommonVector(float a, float b) {
78 if (a > 0 && b > 0) {
79 return a < b ? a : b;
80 } else if (a < 0 && b < 0) {
81 return a > b ? a : b;
82 } else {
83 return 0;
84 }
85}
86
87inline static float distance(float x1, float y1, float x2, float y2) {
88 return hypotf(x1 - x2, y1 - y2);
89}
90
91inline static int32_t signExtendNybble(int32_t value) {
92 return value >= 8 ? value - 16 : value;
93}
94
95// --- RawPointerAxes ---
96
97RawPointerAxes::RawPointerAxes() {
98 clear();
99}
100
101void RawPointerAxes::clear() {
102 x.clear();
103 y.clear();
104 pressure.clear();
105 touchMajor.clear();
106 touchMinor.clear();
107 toolMajor.clear();
108 toolMinor.clear();
109 orientation.clear();
110 distance.clear();
111 tiltX.clear();
112 tiltY.clear();
113 trackingId.clear();
114 slot.clear();
115}
116
117// --- RawPointerData ---
118
119RawPointerData::RawPointerData() {
120 clear();
121}
122
123void RawPointerData::clear() {
124 pointerCount = 0;
125 clearIdBits();
126}
127
128void RawPointerData::copyFrom(const RawPointerData& other) {
129 pointerCount = other.pointerCount;
130 hoveringIdBits = other.hoveringIdBits;
131 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800132 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700133
134 for (uint32_t i = 0; i < pointerCount; i++) {
135 pointers[i] = other.pointers[i];
136
137 int id = pointers[i].id;
138 idToIndex[id] = other.idToIndex[id];
139 }
140}
141
142void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
143 float x = 0, y = 0;
144 uint32_t count = touchingIdBits.count();
145 if (count) {
146 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
147 uint32_t id = idBits.clearFirstMarkedBit();
148 const Pointer& pointer = pointerForId(id);
149 x += pointer.x;
150 y += pointer.y;
151 }
152 x /= count;
153 y /= count;
154 }
155 *outX = x;
156 *outY = y;
157}
158
159// --- CookedPointerData ---
160
161CookedPointerData::CookedPointerData() {
162 clear();
163}
164
165void CookedPointerData::clear() {
166 pointerCount = 0;
167 hoveringIdBits.clear();
168 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800169 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000170 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700171}
172
173void CookedPointerData::copyFrom(const CookedPointerData& other) {
174 pointerCount = other.pointerCount;
175 hoveringIdBits = other.hoveringIdBits;
176 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000177 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700178
179 for (uint32_t i = 0; i < pointerCount; i++) {
180 pointerProperties[i].copyFrom(other.pointerProperties[i]);
181 pointerCoords[i].copyFrom(other.pointerCoords[i]);
182
183 int id = pointerProperties[i].id;
184 idToIndex[id] = other.idToIndex[id];
185 }
186}
187
188// --- TouchInputMapper ---
189
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800190TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
191 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100193 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800194 mRawSurfaceWidth(-1),
195 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700196 mSurfaceLeft(0),
197 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700198 mSurfaceRight(0),
199 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700200 mPhysicalWidth(-1),
201 mPhysicalHeight(-1),
202 mPhysicalLeft(0),
203 mPhysicalTop(0),
204 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
205
206TouchInputMapper::~TouchInputMapper() {}
207
208uint32_t TouchInputMapper::getSources() {
209 return mSource;
210}
211
212void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
213 InputMapper::populateDeviceInfo(info);
214
Michael Wright227c5542020-07-02 18:30:52 +0100215 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700216 info->addMotionRange(mOrientedRanges.x);
217 info->addMotionRange(mOrientedRanges.y);
218 info->addMotionRange(mOrientedRanges.pressure);
219
Chris Yef74dc422020-09-02 22:41:50 -0700220 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700221 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
222 //
223 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
224 // motion, i.e. the hardware dimensions, as the finger could move completely across the
225 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700226 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
227 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
228 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
229 x.fuzz, x.resolution);
230 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
231 y.fuzz, y.resolution);
232 }
233
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700234 if (mOrientedRanges.haveSize) {
235 info->addMotionRange(mOrientedRanges.size);
236 }
237
238 if (mOrientedRanges.haveTouchSize) {
239 info->addMotionRange(mOrientedRanges.touchMajor);
240 info->addMotionRange(mOrientedRanges.touchMinor);
241 }
242
243 if (mOrientedRanges.haveToolSize) {
244 info->addMotionRange(mOrientedRanges.toolMajor);
245 info->addMotionRange(mOrientedRanges.toolMinor);
246 }
247
248 if (mOrientedRanges.haveOrientation) {
249 info->addMotionRange(mOrientedRanges.orientation);
250 }
251
252 if (mOrientedRanges.haveDistance) {
253 info->addMotionRange(mOrientedRanges.distance);
254 }
255
256 if (mOrientedRanges.haveTilt) {
257 info->addMotionRange(mOrientedRanges.tilt);
258 }
259
260 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
261 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
262 0.0f);
263 }
264 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
265 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
266 0.0f);
267 }
Michael Wright227c5542020-07-02 18:30:52 +0100268 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700269 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
270 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
271 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
272 x.fuzz, x.resolution);
273 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
274 y.fuzz, y.resolution);
275 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
276 x.fuzz, x.resolution);
277 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
278 y.fuzz, y.resolution);
279 }
280 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
281 }
282}
283
284void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700285 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
286 NamedEnum::string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700287 dumpParameters(dump);
288 dumpVirtualKeys(dump);
289 dumpRawPointerAxes(dump);
290 dumpCalibration(dump);
291 dumpAffineTransformation(dump);
292 dumpSurface(dump);
293
294 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
295 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
296 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
297 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
298 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
299 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
300 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
301 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
302 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
303 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
304 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
305 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
306 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
307 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
308 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
309 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
310 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
311
312 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
313 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
314 mLastRawState.rawPointerData.pointerCount);
315 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
316 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
317 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
318 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
319 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
320 "toolType=%d, isHovering=%s\n",
321 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
322 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
323 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
324 pointer.distance, pointer.toolType, toString(pointer.isHovering));
325 }
326
327 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
328 mLastCookedState.buttonState);
329 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
330 mLastCookedState.cookedPointerData.pointerCount);
331 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
332 const PointerProperties& pointerProperties =
333 mLastCookedState.cookedPointerData.pointerProperties[i];
334 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000335 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
336 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
337 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700338 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
339 "toolType=%d, isHovering=%s\n",
340 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000341 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
342 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700343 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
344 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
345 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
346 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
347 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
348 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
349 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
350 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
351 pointerProperties.toolType,
352 toString(mLastCookedState.cookedPointerData.isHovering(i)));
353 }
354
355 dump += INDENT3 "Stylus Fusion:\n";
356 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
357 toString(mExternalStylusConnected));
358 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
359 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
360 mExternalStylusFusionTimeout);
361 dump += INDENT3 "External Stylus State:\n";
362 dumpStylusState(dump, mExternalStylusState);
363
Michael Wright227c5542020-07-02 18:30:52 +0100364 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700365 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
366 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
367 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
368 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
369 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
370 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
371 }
372}
373
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
375 uint32_t changes) {
376 InputMapper::configure(when, config, changes);
377
378 mConfig = *config;
379
380 if (!changes) { // first time only
381 // Configure basic parameters.
382 configureParameters();
383
384 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800385 mCursorScrollAccumulator.configure(getDeviceContext());
386 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700387
388 // Configure absolute axis information.
389 configureRawPointerAxes();
390
391 // Prepare input device calibration.
392 parseCalibration();
393 resolveCalibration();
394 }
395
396 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
397 // Update location calibration to reflect current settings
398 updateAffineTransformation();
399 }
400
401 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
402 // Update pointer speed.
403 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
404 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
405 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
406 }
407
408 bool resetNeeded = false;
409 if (!changes ||
410 (changes &
411 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800412 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700413 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
414 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
415 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
416 // Configure device sources, surface dimensions, orientation and
417 // scaling factors.
418 configureSurface(when, &resetNeeded);
419 }
420
421 if (changes && resetNeeded) {
422 // Send reset, unless this is the first time the device has been configured,
423 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +0000424 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
425 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426 }
427}
428
429void TouchInputMapper::resolveExternalStylusPresence() {
430 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800431 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700432 mExternalStylusConnected = !devices.empty();
433
434 if (!mExternalStylusConnected) {
435 resetExternalStylus();
436 }
437}
438
439void TouchInputMapper::configureParameters() {
440 // Use the pointer presentation mode for devices that do not support distinct
441 // multitouch. The spot-based presentation relies on being able to accurately
442 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800443 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100444 ? Parameters::GestureMode::SINGLE_TOUCH
445 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446
447 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800448 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
449 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100451 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100453 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700454 } else if (gestureModeString != "default") {
455 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
456 }
457 }
458
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800459 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100461 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800462 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100464 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800465 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
466 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700467 // The device is a cursor device with a touch pad attached.
468 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100469 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700470 } else {
471 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100472 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700473 }
474
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800475 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700476
477 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800478 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
479 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700480 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100481 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700482 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100483 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100485 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700486 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100487 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488 } else if (deviceTypeString != "default") {
489 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
490 }
491 }
492
Michael Wright227c5542020-07-02 18:30:52 +0100493 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
495 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496
497 mParameters.hasAssociatedDisplay = false;
498 mParameters.associatedDisplayIsExternal = false;
499 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100500 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
501 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100503 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800504 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700505 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800506 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
507 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700508 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
509 }
510 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800511 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700512 mParameters.hasAssociatedDisplay = true;
513 }
514
515 // Initial downs on external touch devices should wake the device.
516 // Normally we don't do this for internal touch screens to prevent them from waking
517 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800518 mParameters.wake = getDeviceContext().isExternal();
519 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700520}
521
522void TouchInputMapper::dumpParameters(std::string& dump) {
523 dump += INDENT3 "Parameters:\n";
524
Chris Yea03dd232020-09-08 19:21:09 -0700525 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700526
Chris Yea03dd232020-09-08 19:21:09 -0700527 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700528
529 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
530 "displayId='%s'\n",
531 toString(mParameters.hasAssociatedDisplay),
532 toString(mParameters.associatedDisplayIsExternal),
533 mParameters.uniqueDisplayId.c_str());
534 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
535}
536
537void TouchInputMapper::configureRawPointerAxes() {
538 mRawPointerAxes.clear();
539}
540
541void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
542 dump += INDENT3 "Raw Touch Axes:\n";
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
549 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
550 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
551 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
552 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
553 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
554 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
555 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
556}
557
558bool TouchInputMapper::hasExternalStylus() const {
559 return mExternalStylusConnected;
560}
561
562/**
563 * Determine which DisplayViewport to use.
564 * 1. If display port is specified, return the matching viewport. If matching viewport not
565 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800566 * 2. Always use the suggested viewport from WindowManagerService for pointers.
567 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700568 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800569 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700570 */
571std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800572 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800573 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700574 if (displayPort) {
575 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800576 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700577 }
578
Michael Wright227c5542020-07-02 18:30:52 +0100579 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800580 std::optional<DisplayViewport> viewport =
581 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
582 if (viewport) {
583 return viewport;
584 } else {
585 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
586 mConfig.defaultPointerDisplayId);
587 }
588 }
589
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700590 // Check if uniqueDisplayId is specified in idc file.
591 if (!mParameters.uniqueDisplayId.empty()) {
592 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
593 }
594
595 ViewportType viewportTypeToUse;
596 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100597 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700598 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100599 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700600 }
601
602 std::optional<DisplayViewport> viewport =
603 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100604 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700605 ALOGW("Input device %s should be associated with external display, "
606 "fallback to internal one for the external viewport is not found.",
607 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100608 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700609 }
610
611 return viewport;
612 }
613
614 // No associated display, return a non-display viewport.
615 DisplayViewport newViewport;
616 // Raw width and height in the natural orientation.
617 int32_t rawWidth = mRawPointerAxes.getRawWidth();
618 int32_t rawHeight = mRawPointerAxes.getRawHeight();
619 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
620 return std::make_optional(newViewport);
621}
622
623void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100624 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700625
626 resolveExternalStylusPresence();
627
628 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100629 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800630 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700631 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100632 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700633 if (hasStylus()) {
634 mSource |= AINPUT_SOURCE_STYLUS;
635 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800636 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700637 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100638 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700639 if (hasStylus()) {
640 mSource |= AINPUT_SOURCE_STYLUS;
641 }
642 if (hasExternalStylus()) {
643 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
644 }
Michael Wright227c5542020-07-02 18:30:52 +0100645 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700646 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100647 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700648 } else {
649 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100650 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700651 }
652
653 // Ensure we have valid X and Y axes.
654 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
655 ALOGW("Touch device '%s' did not report support for X or Y axis! "
656 "The device will be inoperable.",
657 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100658 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700659 return;
660 }
661
662 // Get associated display dimensions.
663 std::optional<DisplayViewport> newViewport = findViewport();
664 if (!newViewport) {
665 ALOGI("Touch device '%s' could not query the properties of its associated "
666 "display. The device will be inoperable until the display size "
667 "becomes available.",
668 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100669 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700670 return;
671 }
672
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000673 if (!newViewport->isActive) {
674 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
675 getDeviceName().c_str(), getDeviceId());
676 mDeviceMode = DeviceMode::DISABLED;
677 return;
678 }
679
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700680 // Raw width and height in the natural orientation.
681 int32_t rawWidth = mRawPointerAxes.getRawWidth();
682 int32_t rawHeight = mRawPointerAxes.getRawHeight();
683
684 bool viewportChanged = mViewport != *newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700685 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700686 if (viewportChanged) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700687 bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700688 mViewport = *newViewport;
689
Michael Wright227c5542020-07-02 18:30:52 +0100690 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700691 // Convert rotated viewport to natural surface coordinates.
692 int32_t naturalLogicalWidth, naturalLogicalHeight;
693 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
694 int32_t naturalPhysicalLeft, naturalPhysicalTop;
695 int32_t naturalDeviceWidth, naturalDeviceHeight;
696 switch (mViewport.orientation) {
697 case DISPLAY_ORIENTATION_90:
698 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
699 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
700 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
701 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800702 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700703 naturalPhysicalTop = mViewport.physicalLeft;
704 naturalDeviceWidth = mViewport.deviceHeight;
705 naturalDeviceHeight = mViewport.deviceWidth;
706 break;
707 case DISPLAY_ORIENTATION_180:
708 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
709 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
710 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
711 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
712 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
713 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
714 naturalDeviceWidth = mViewport.deviceWidth;
715 naturalDeviceHeight = mViewport.deviceHeight;
716 break;
717 case DISPLAY_ORIENTATION_270:
718 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
719 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
720 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
721 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
722 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800723 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700724 naturalDeviceWidth = mViewport.deviceHeight;
725 naturalDeviceHeight = mViewport.deviceWidth;
726 break;
727 case DISPLAY_ORIENTATION_0:
728 default:
729 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
730 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
731 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
732 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
733 naturalPhysicalLeft = mViewport.physicalLeft;
734 naturalPhysicalTop = mViewport.physicalTop;
735 naturalDeviceWidth = mViewport.deviceWidth;
736 naturalDeviceHeight = mViewport.deviceHeight;
737 break;
738 }
739
740 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
741 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
742 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
743 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
744 }
745
746 mPhysicalWidth = naturalPhysicalWidth;
747 mPhysicalHeight = naturalPhysicalHeight;
748 mPhysicalLeft = naturalPhysicalLeft;
749 mPhysicalTop = naturalPhysicalTop;
750
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700751 const int32_t oldSurfaceWidth = mRawSurfaceWidth;
752 const int32_t oldSurfaceHeight = mRawSurfaceHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800753 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
754 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700755 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
756 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800757 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
758 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700759
Prabir Pradhand7482e72021-03-09 13:54:55 -0800760 if (isPerWindowInputRotationEnabled()) {
761 // When per-window input rotation is enabled, InputReader works in the un-rotated
762 // coordinate space, so we don't need to do anything if the device is already
763 // orientation-aware. If the device is not orientation-aware, then we need to apply
764 // the inverse rotation of the display so that when the display rotation is applied
765 // later as a part of the per-window transform, we get the expected screen
766 // coordinates.
767 mSurfaceOrientation = mParameters.orientationAware
768 ? DISPLAY_ORIENTATION_0
769 : getInverseRotation(mViewport.orientation);
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700770 // For orientation-aware devices that work in the un-rotated coordinate space, the
771 // viewport update should be skipped if it is only a change in the orientation.
772 skipViewportUpdate = mParameters.orientationAware &&
773 mRawSurfaceWidth == oldSurfaceWidth &&
774 mRawSurfaceHeight == oldSurfaceHeight && viewportOrientationChanged;
Prabir Pradhand7482e72021-03-09 13:54:55 -0800775 } else {
776 mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation
777 : DISPLAY_ORIENTATION_0;
778 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700779 } else {
780 mPhysicalWidth = rawWidth;
781 mPhysicalHeight = rawHeight;
782 mPhysicalLeft = 0;
783 mPhysicalTop = 0;
784
Arthur Hung4197f6b2020-03-16 15:39:59 +0800785 mRawSurfaceWidth = rawWidth;
786 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700787 mSurfaceLeft = 0;
788 mSurfaceTop = 0;
789 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
790 }
791 }
792
793 // If moving between pointer modes, need to reset some state.
794 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
795 if (deviceModeChanged) {
796 mOrientedRanges.clear();
797 }
798
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800799 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
800 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100801 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800802 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
803 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800804 if (mPointerController == nullptr) {
805 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700806 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800807 if (mConfig.pointerCapture) {
808 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
809 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700810 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100811 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700812 }
813
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700814 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700815 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
816 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800817 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700818 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
819
820 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800821 mXScale = float(mRawSurfaceWidth) / rawWidth;
822 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700823 mXTranslate = -mSurfaceLeft;
824 mYTranslate = -mSurfaceTop;
825 mXPrecision = 1.0f / mXScale;
826 mYPrecision = 1.0f / mYScale;
827
828 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
829 mOrientedRanges.x.source = mSource;
830 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
831 mOrientedRanges.y.source = mSource;
832
833 configureVirtualKeys();
834
835 // Scale factor for terms that are not oriented in a particular axis.
836 // If the pixels are square then xScale == yScale otherwise we fake it
837 // by choosing an average.
838 mGeometricScale = avg(mXScale, mYScale);
839
840 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800841 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700842
843 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100844 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700845 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
846 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
847 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
848 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
849 } else {
850 mSizeScale = 0.0f;
851 }
852
853 mOrientedRanges.haveTouchSize = true;
854 mOrientedRanges.haveToolSize = true;
855 mOrientedRanges.haveSize = true;
856
857 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
858 mOrientedRanges.touchMajor.source = mSource;
859 mOrientedRanges.touchMajor.min = 0;
860 mOrientedRanges.touchMajor.max = diagonalSize;
861 mOrientedRanges.touchMajor.flat = 0;
862 mOrientedRanges.touchMajor.fuzz = 0;
863 mOrientedRanges.touchMajor.resolution = 0;
864
865 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
866 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
867
868 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
869 mOrientedRanges.toolMajor.source = mSource;
870 mOrientedRanges.toolMajor.min = 0;
871 mOrientedRanges.toolMajor.max = diagonalSize;
872 mOrientedRanges.toolMajor.flat = 0;
873 mOrientedRanges.toolMajor.fuzz = 0;
874 mOrientedRanges.toolMajor.resolution = 0;
875
876 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
877 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
878
879 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
880 mOrientedRanges.size.source = mSource;
881 mOrientedRanges.size.min = 0;
882 mOrientedRanges.size.max = 1.0;
883 mOrientedRanges.size.flat = 0;
884 mOrientedRanges.size.fuzz = 0;
885 mOrientedRanges.size.resolution = 0;
886 } else {
887 mSizeScale = 0.0f;
888 }
889
890 // Pressure factors.
891 mPressureScale = 0;
892 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100893 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
894 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700895 if (mCalibration.havePressureScale) {
896 mPressureScale = mCalibration.pressureScale;
897 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
898 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
899 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
900 }
901 }
902
903 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
904 mOrientedRanges.pressure.source = mSource;
905 mOrientedRanges.pressure.min = 0;
906 mOrientedRanges.pressure.max = pressureMax;
907 mOrientedRanges.pressure.flat = 0;
908 mOrientedRanges.pressure.fuzz = 0;
909 mOrientedRanges.pressure.resolution = 0;
910
911 // Tilt
912 mTiltXCenter = 0;
913 mTiltXScale = 0;
914 mTiltYCenter = 0;
915 mTiltYScale = 0;
916 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
917 if (mHaveTilt) {
918 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
919 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
920 mTiltXScale = M_PI / 180;
921 mTiltYScale = M_PI / 180;
922
923 mOrientedRanges.haveTilt = true;
924
925 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
926 mOrientedRanges.tilt.source = mSource;
927 mOrientedRanges.tilt.min = 0;
928 mOrientedRanges.tilt.max = M_PI_2;
929 mOrientedRanges.tilt.flat = 0;
930 mOrientedRanges.tilt.fuzz = 0;
931 mOrientedRanges.tilt.resolution = 0;
932 }
933
934 // Orientation
935 mOrientationScale = 0;
936 if (mHaveTilt) {
937 mOrientedRanges.haveOrientation = true;
938
939 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
940 mOrientedRanges.orientation.source = mSource;
941 mOrientedRanges.orientation.min = -M_PI;
942 mOrientedRanges.orientation.max = M_PI;
943 mOrientedRanges.orientation.flat = 0;
944 mOrientedRanges.orientation.fuzz = 0;
945 mOrientedRanges.orientation.resolution = 0;
946 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100947 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700948 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100949 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700950 if (mRawPointerAxes.orientation.valid) {
951 if (mRawPointerAxes.orientation.maxValue > 0) {
952 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
953 } else if (mRawPointerAxes.orientation.minValue < 0) {
954 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
955 } else {
956 mOrientationScale = 0;
957 }
958 }
959 }
960
961 mOrientedRanges.haveOrientation = true;
962
963 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
964 mOrientedRanges.orientation.source = mSource;
965 mOrientedRanges.orientation.min = -M_PI_2;
966 mOrientedRanges.orientation.max = M_PI_2;
967 mOrientedRanges.orientation.flat = 0;
968 mOrientedRanges.orientation.fuzz = 0;
969 mOrientedRanges.orientation.resolution = 0;
970 }
971
972 // Distance
973 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100974 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
975 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700976 if (mCalibration.haveDistanceScale) {
977 mDistanceScale = mCalibration.distanceScale;
978 } else {
979 mDistanceScale = 1.0f;
980 }
981 }
982
983 mOrientedRanges.haveDistance = true;
984
985 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
986 mOrientedRanges.distance.source = mSource;
987 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
988 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
989 mOrientedRanges.distance.flat = 0;
990 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
991 mOrientedRanges.distance.resolution = 0;
992 }
993
994 // Compute oriented precision, scales and ranges.
995 // Note that the maximum value reported is an inclusive maximum value so it is one
996 // unit less than the total width or height of surface.
997 switch (mSurfaceOrientation) {
998 case DISPLAY_ORIENTATION_90:
999 case DISPLAY_ORIENTATION_270:
1000 mOrientedXPrecision = mYPrecision;
1001 mOrientedYPrecision = mXPrecision;
1002
1003 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001004 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001005 mOrientedRanges.x.flat = 0;
1006 mOrientedRanges.x.fuzz = 0;
1007 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
1008
1009 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001010 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011 mOrientedRanges.y.flat = 0;
1012 mOrientedRanges.y.fuzz = 0;
1013 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
1014 break;
1015
1016 default:
1017 mOrientedXPrecision = mXPrecision;
1018 mOrientedYPrecision = mYPrecision;
1019
1020 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001021 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001022 mOrientedRanges.x.flat = 0;
1023 mOrientedRanges.x.fuzz = 0;
1024 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1025
1026 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001027 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001028 mOrientedRanges.y.flat = 0;
1029 mOrientedRanges.y.fuzz = 0;
1030 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1031 break;
1032 }
1033
1034 // Location
1035 updateAffineTransformation();
1036
Michael Wright227c5542020-07-02 18:30:52 +01001037 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001038 // Compute pointer gesture detection parameters.
1039 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001040 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001041
1042 // Scale movements such that one whole swipe of the touch pad covers a
1043 // given area relative to the diagonal size of the display when no acceleration
1044 // is applied.
1045 // Assume that the touch pad has a square aspect ratio such that movements in
1046 // X and Y of the same number of raw units cover the same physical distance.
1047 mPointerXMovementScale =
1048 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1049 mPointerYMovementScale = mPointerXMovementScale;
1050
1051 // Scale zooms to cover a smaller range of the display than movements do.
1052 // This value determines the area around the pointer that is affected by freeform
1053 // pointer gestures.
1054 mPointerXZoomScale =
1055 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1056 mPointerYZoomScale = mPointerXZoomScale;
1057
1058 // Max width between pointers to detect a swipe gesture is more than some fraction
1059 // of the diagonal axis of the touch pad. Touches that are wider than this are
1060 // translated into freeform gestures.
1061 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1062
1063 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001064 const nsecs_t readTime = when; // synthetic event
1065 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066 }
1067
1068 // Inform the dispatcher about the changes.
1069 *outResetNeeded = true;
1070 bumpGeneration();
1071 }
1072}
1073
1074void TouchInputMapper::dumpSurface(std::string& dump) {
1075 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001076 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1077 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001078 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1079 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001080 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1081 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1083 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1084 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1085 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1086 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1087}
1088
1089void TouchInputMapper::configureVirtualKeys() {
1090 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001091 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092
1093 mVirtualKeys.clear();
1094
1095 if (virtualKeyDefinitions.size() == 0) {
1096 return;
1097 }
1098
1099 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1100 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1101 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1102 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1103
1104 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1105 VirtualKey virtualKey;
1106
1107 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1108 int32_t keyCode;
1109 int32_t dummyKeyMetaState;
1110 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001111 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1112 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1114 continue; // drop the key
1115 }
1116
1117 virtualKey.keyCode = keyCode;
1118 virtualKey.flags = flags;
1119
1120 // convert the key definition's display coordinates into touch coordinates for a hit box
1121 int32_t halfWidth = virtualKeyDefinition.width / 2;
1122 int32_t halfHeight = virtualKeyDefinition.height / 2;
1123
1124 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001125 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 touchScreenLeft;
1127 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001128 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001129 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001130 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1131 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001133 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1134 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 touchScreenTop;
1136 mVirtualKeys.push_back(virtualKey);
1137 }
1138}
1139
1140void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1141 if (!mVirtualKeys.empty()) {
1142 dump += INDENT3 "Virtual Keys:\n";
1143
1144 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1145 const VirtualKey& virtualKey = mVirtualKeys[i];
1146 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1147 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1148 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1149 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1150 }
1151 }
1152}
1153
1154void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001155 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001156 Calibration& out = mCalibration;
1157
1158 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001159 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 String8 sizeCalibrationString;
1161 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1162 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001164 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001165 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (sizeCalibrationString != "default") {
1173 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1174 }
1175 }
1176
1177 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1178 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1179 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1180
1181 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001182 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183 String8 pressureCalibrationString;
1184 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1185 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001186 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001187 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (pressureCalibrationString != "default") {
1192 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1193 pressureCalibrationString.string());
1194 }
1195 }
1196
1197 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1198
1199 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 String8 orientationCalibrationString;
1202 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1203 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 } else if (orientationCalibrationString != "default") {
1210 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1211 orientationCalibrationString.string());
1212 }
1213 }
1214
1215 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 String8 distanceCalibrationString;
1218 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1219 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001220 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 } else if (distanceCalibrationString != "default") {
1224 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1225 distanceCalibrationString.string());
1226 }
1227 }
1228
1229 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1230
Michael Wright227c5542020-07-02 18:30:52 +01001231 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 String8 coverageCalibrationString;
1233 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1234 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001235 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001237 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 } else if (coverageCalibrationString != "default") {
1239 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1240 coverageCalibrationString.string());
1241 }
1242 }
1243}
1244
1245void TouchInputMapper::resolveCalibration() {
1246 // Size
1247 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001248 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1249 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001252 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 }
1254
1255 // Pressure
1256 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001257 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1258 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001261 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263
1264 // Orientation
1265 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001266 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1267 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 }
1269 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001270 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272
1273 // Distance
1274 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001275 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1276 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 }
1278 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001279 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 }
1281
1282 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001283 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1284 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 }
1286}
1287
1288void TouchInputMapper::dumpCalibration(std::string& dump) {
1289 dump += INDENT3 "Calibration:\n";
1290
1291 // Size
1292 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001293 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 dump += INDENT4 "touch.size.calibration: none\n";
1295 break;
Michael Wright227c5542020-07-02 18:30:52 +01001296 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 dump += INDENT4 "touch.size.calibration: geometric\n";
1298 break;
Michael Wright227c5542020-07-02 18:30:52 +01001299 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 dump += INDENT4 "touch.size.calibration: diameter\n";
1301 break;
Michael Wright227c5542020-07-02 18:30:52 +01001302 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 dump += INDENT4 "touch.size.calibration: box\n";
1304 break;
Michael Wright227c5542020-07-02 18:30:52 +01001305 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 dump += INDENT4 "touch.size.calibration: area\n";
1307 break;
1308 default:
1309 ALOG_ASSERT(false);
1310 }
1311
1312 if (mCalibration.haveSizeScale) {
1313 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1314 }
1315
1316 if (mCalibration.haveSizeBias) {
1317 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1318 }
1319
1320 if (mCalibration.haveSizeIsSummed) {
1321 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1322 toString(mCalibration.sizeIsSummed));
1323 }
1324
1325 // Pressure
1326 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001327 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.pressure.calibration: none\n";
1329 break;
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.pressure.calibration: physical\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1335 break;
1336 default:
1337 ALOG_ASSERT(false);
1338 }
1339
1340 if (mCalibration.havePressureScale) {
1341 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1342 }
1343
1344 // Orientation
1345 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001346 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001347 dump += INDENT4 "touch.orientation.calibration: none\n";
1348 break;
Michael Wright227c5542020-07-02 18:30:52 +01001349 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1351 break;
Michael Wright227c5542020-07-02 18:30:52 +01001352 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 dump += INDENT4 "touch.orientation.calibration: vector\n";
1354 break;
1355 default:
1356 ALOG_ASSERT(false);
1357 }
1358
1359 // Distance
1360 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001361 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001362 dump += INDENT4 "touch.distance.calibration: none\n";
1363 break;
Michael Wright227c5542020-07-02 18:30:52 +01001364 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001365 dump += INDENT4 "touch.distance.calibration: scaled\n";
1366 break;
1367 default:
1368 ALOG_ASSERT(false);
1369 }
1370
1371 if (mCalibration.haveDistanceScale) {
1372 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1373 }
1374
1375 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001376 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001377 dump += INDENT4 "touch.coverage.calibration: none\n";
1378 break;
Michael Wright227c5542020-07-02 18:30:52 +01001379 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001380 dump += INDENT4 "touch.coverage.calibration: box\n";
1381 break;
1382 default:
1383 ALOG_ASSERT(false);
1384 }
1385}
1386
1387void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1388 dump += INDENT3 "Affine Transformation:\n";
1389
1390 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1391 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1392 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1393 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1394 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1395 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1396}
1397
1398void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001399 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001400 mSurfaceOrientation);
1401}
1402
1403void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001404 mCursorButtonAccumulator.reset(getDeviceContext());
1405 mCursorScrollAccumulator.reset(getDeviceContext());
1406 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407
1408 mPointerVelocityControl.reset();
1409 mWheelXVelocityControl.reset();
1410 mWheelYVelocityControl.reset();
1411
1412 mRawStatesPending.clear();
1413 mCurrentRawState.clear();
1414 mCurrentCookedState.clear();
1415 mLastRawState.clear();
1416 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001417 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001418 mSentHoverEnter = false;
1419 mHavePointerIds = false;
1420 mCurrentMotionAborted = false;
1421 mDownTime = 0;
1422
1423 mCurrentVirtualKey.down = false;
1424
1425 mPointerGesture.reset();
1426 mPointerSimple.reset();
1427 resetExternalStylus();
1428
1429 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001430 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431 mPointerController->clearSpots();
1432 }
1433
1434 InputMapper::reset(when);
1435}
1436
1437void TouchInputMapper::resetExternalStylus() {
1438 mExternalStylusState.clear();
1439 mExternalStylusId = -1;
1440 mExternalStylusFusionTimeout = LLONG_MAX;
1441 mExternalStylusDataPending = false;
1442}
1443
1444void TouchInputMapper::clearStylusDataPendingFlags() {
1445 mExternalStylusDataPending = false;
1446 mExternalStylusFusionTimeout = LLONG_MAX;
1447}
1448
1449void TouchInputMapper::process(const RawEvent* rawEvent) {
1450 mCursorButtonAccumulator.process(rawEvent);
1451 mCursorScrollAccumulator.process(rawEvent);
1452 mTouchButtonAccumulator.process(rawEvent);
1453
1454 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001455 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456 }
1457}
1458
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001459void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001460 // Push a new state.
1461 mRawStatesPending.emplace_back();
1462
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001463 RawState& next = mRawStatesPending.back();
1464 next.clear();
1465 next.when = when;
1466 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001467
1468 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001469 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001470 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1471
1472 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001473 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1474 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001475 mCursorScrollAccumulator.finishSync();
1476
1477 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001478 syncTouch(when, &next);
1479
1480 // The last RawState is the actually second to last, since we just added a new state
1481 const RawState& last =
1482 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001483
1484 // Assign pointer ids.
1485 if (!mHavePointerIds) {
1486 assignPointerIds(last, next);
1487 }
1488
1489#if DEBUG_RAW_EVENTS
1490 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001491 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001492 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1493 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1494 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1495 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496#endif
1497
1498 processRawTouches(false /*timeout*/);
1499}
1500
1501void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001502 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001503 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001504 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001505 mCurrentCookedState.clear();
1506 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001507 return;
1508 }
1509
1510 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1511 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1512 // touching the current state will only observe the events that have been dispatched to the
1513 // rest of the pipeline.
1514 const size_t N = mRawStatesPending.size();
1515 size_t count;
1516 for (count = 0; count < N; count++) {
1517 const RawState& next = mRawStatesPending[count];
1518
1519 // A failure to assign the stylus id means that we're waiting on stylus data
1520 // and so should defer the rest of the pipeline.
1521 if (assignExternalStylusId(next, timeout)) {
1522 break;
1523 }
1524
1525 // All ready to go.
1526 clearStylusDataPendingFlags();
1527 mCurrentRawState.copyFrom(next);
1528 if (mCurrentRawState.when < mLastRawState.when) {
1529 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001530 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001531 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001532 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001533 }
1534 if (count != 0) {
1535 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1536 }
1537
1538 if (mExternalStylusDataPending) {
1539 if (timeout) {
1540 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1541 clearStylusDataPendingFlags();
1542 mCurrentRawState.copyFrom(mLastRawState);
1543#if DEBUG_STYLUS_FUSION
1544 ALOGD("Timeout expired, synthesizing event with new stylus data");
1545#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001546 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1547 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001548 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1549 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1550 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1551 }
1552 }
1553}
1554
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001555void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001556 // Always start with a clean state.
1557 mCurrentCookedState.clear();
1558
1559 // Apply stylus buttons to current raw state.
1560 applyExternalStylusButtonState(when);
1561
1562 // Handle policy on initial down or hover events.
1563 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1564 mCurrentRawState.rawPointerData.pointerCount != 0;
1565
1566 uint32_t policyFlags = 0;
1567 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1568 if (initialDown || buttonsPressed) {
1569 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001570 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001571 getContext()->fadePointer();
1572 }
1573
1574 if (mParameters.wake) {
1575 policyFlags |= POLICY_FLAG_WAKE;
1576 }
1577 }
1578
1579 // Consume raw off-screen touches before cooking pointer data.
1580 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001581 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001582 mCurrentRawState.rawPointerData.clear();
1583 }
1584
1585 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1586 // with cooked pointer data that has the same ids and indices as the raw data.
1587 // The following code can use either the raw or cooked data, as needed.
1588 cookPointerData();
1589
1590 // Apply stylus pressure to current cooked state.
1591 applyExternalStylusTouchState(when);
1592
1593 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001594 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1595 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596 mCurrentCookedState.buttonState);
1597
1598 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001599 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001600 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1601 uint32_t id = idBits.clearFirstMarkedBit();
1602 const RawPointerData::Pointer& pointer =
1603 mCurrentRawState.rawPointerData.pointerForId(id);
1604 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1605 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1606 mCurrentCookedState.stylusIdBits.markBit(id);
1607 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1608 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1609 mCurrentCookedState.fingerIdBits.markBit(id);
1610 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1611 mCurrentCookedState.mouseIdBits.markBit(id);
1612 }
1613 }
1614 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1615 uint32_t id = idBits.clearFirstMarkedBit();
1616 const RawPointerData::Pointer& pointer =
1617 mCurrentRawState.rawPointerData.pointerForId(id);
1618 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1619 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1620 mCurrentCookedState.stylusIdBits.markBit(id);
1621 }
1622 }
1623
1624 // Stylus takes precedence over all tools, then mouse, then finger.
1625 PointerUsage pointerUsage = mPointerUsage;
1626 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1627 mCurrentCookedState.mouseIdBits.clear();
1628 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001629 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1631 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001632 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001633 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1634 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001635 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636 }
1637
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001638 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001639 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001640 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001641
1642 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001643 dispatchButtonRelease(when, readTime, policyFlags);
1644 dispatchHoverExit(when, readTime, policyFlags);
1645 dispatchTouches(when, readTime, policyFlags);
1646 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1647 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001648 }
1649
1650 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1651 mCurrentMotionAborted = false;
1652 }
1653 }
1654
1655 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001656 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001657 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1658 mCurrentCookedState.buttonState);
1659
1660 // Clear some transient state.
1661 mCurrentRawState.rawVScroll = 0;
1662 mCurrentRawState.rawHScroll = 0;
1663
1664 // Copy current touch to last touch in preparation for the next cycle.
1665 mLastRawState.copyFrom(mCurrentRawState);
1666 mLastCookedState.copyFrom(mCurrentCookedState);
1667}
1668
Garfield Tanc734e4f2021-01-15 20:01:39 -08001669void TouchInputMapper::updateTouchSpots() {
1670 if (!mConfig.showTouches || mPointerController == nullptr) {
1671 return;
1672 }
1673
1674 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1675 // clear touch spots.
1676 if (mDeviceMode != DeviceMode::DIRECT &&
1677 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1678 return;
1679 }
1680
1681 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1682 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1683
1684 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001685 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1686 mCurrentCookedState.cookedPointerData.idToIndex,
1687 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001688}
1689
1690bool TouchInputMapper::isTouchScreen() {
1691 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1692 mParameters.hasAssociatedDisplay;
1693}
1694
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001695void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001696 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001697 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1698 }
1699}
1700
1701void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1702 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1703 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1704
1705 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1706 float pressure = mExternalStylusState.pressure;
1707 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1708 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1709 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1710 }
1711 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1712 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1713
1714 PointerProperties& properties =
1715 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1716 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1717 properties.toolType = mExternalStylusState.toolType;
1718 }
1719 }
1720}
1721
1722bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001723 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001724 return false;
1725 }
1726
1727 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1728 state.rawPointerData.pointerCount != 0;
1729 if (initialDown) {
1730 if (mExternalStylusState.pressure != 0.0f) {
1731#if DEBUG_STYLUS_FUSION
1732 ALOGD("Have both stylus and touch data, beginning fusion");
1733#endif
1734 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1735 } else if (timeout) {
1736#if DEBUG_STYLUS_FUSION
1737 ALOGD("Timeout expired, assuming touch is not a stylus.");
1738#endif
1739 resetExternalStylus();
1740 } else {
1741 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1742 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1743 }
1744#if DEBUG_STYLUS_FUSION
1745 ALOGD("No stylus data but stylus is connected, requesting timeout "
1746 "(%" PRId64 "ms)",
1747 mExternalStylusFusionTimeout);
1748#endif
1749 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1750 return true;
1751 }
1752 }
1753
1754 // Check if the stylus pointer has gone up.
1755 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1756#if DEBUG_STYLUS_FUSION
1757 ALOGD("Stylus pointer is going up");
1758#endif
1759 mExternalStylusId = -1;
1760 }
1761
1762 return false;
1763}
1764
1765void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001766 if (mDeviceMode == DeviceMode::POINTER) {
1767 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001768 // Since this is a synthetic event, we can consider its latency to be zero
1769 const nsecs_t readTime = when;
1770 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001771 }
Michael Wright227c5542020-07-02 18:30:52 +01001772 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001773 if (mExternalStylusFusionTimeout < when) {
1774 processRawTouches(true /*timeout*/);
1775 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1776 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1777 }
1778 }
1779}
1780
1781void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1782 mExternalStylusState.copyFrom(state);
1783 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1784 // We're either in the middle of a fused stream of data or we're waiting on data before
1785 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1786 // data.
1787 mExternalStylusDataPending = true;
1788 processRawTouches(false /*timeout*/);
1789 }
1790}
1791
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001792bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793 // Check for release of a virtual key.
1794 if (mCurrentVirtualKey.down) {
1795 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1796 // Pointer went up while virtual key was down.
1797 mCurrentVirtualKey.down = false;
1798 if (!mCurrentVirtualKey.ignored) {
1799#if DEBUG_VIRTUAL_KEYS
1800 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1801 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1802#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001803 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001804 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1805 }
1806 return true;
1807 }
1808
1809 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1810 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1811 const RawPointerData::Pointer& pointer =
1812 mCurrentRawState.rawPointerData.pointerForId(id);
1813 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1814 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1815 // Pointer is still within the space of the virtual key.
1816 return true;
1817 }
1818 }
1819
1820 // Pointer left virtual key area or another pointer also went down.
1821 // Send key cancellation but do not consume the touch yet.
1822 // This is useful when the user swipes through from the virtual key area
1823 // into the main display surface.
1824 mCurrentVirtualKey.down = false;
1825 if (!mCurrentVirtualKey.ignored) {
1826#if DEBUG_VIRTUAL_KEYS
1827 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1828 mCurrentVirtualKey.scanCode);
1829#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001830 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001831 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1832 AKEY_EVENT_FLAG_CANCELED);
1833 }
1834 }
1835
1836 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1837 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1838 // Pointer just went down. Check for virtual key press or off-screen touches.
1839 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1840 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001841 // Exclude unscaled device for inside surface checking.
1842 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001843 // If exactly one pointer went down, check for virtual key hit.
1844 // Otherwise we will drop the entire stroke.
1845 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1846 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1847 if (virtualKey) {
1848 mCurrentVirtualKey.down = true;
1849 mCurrentVirtualKey.downTime = when;
1850 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1851 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1852 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001853 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1854 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001855
1856 if (!mCurrentVirtualKey.ignored) {
1857#if DEBUG_VIRTUAL_KEYS
1858 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1859 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1860#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001861 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001862 AKEY_EVENT_FLAG_FROM_SYSTEM |
1863 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1864 }
1865 }
1866 }
1867 return true;
1868 }
1869 }
1870
1871 // Disable all virtual key touches that happen within a short time interval of the
1872 // most recent touch within the screen area. The idea is to filter out stray
1873 // virtual key presses when interacting with the touch screen.
1874 //
1875 // Problems we're trying to solve:
1876 //
1877 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1878 // virtual key area that is implemented by a separate touch panel and accidentally
1879 // triggers a virtual key.
1880 //
1881 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1882 // area and accidentally triggers a virtual key. This often happens when virtual keys
1883 // are layed out below the screen near to where the on screen keyboard's space bar
1884 // is displayed.
1885 if (mConfig.virtualKeyQuietTime > 0 &&
1886 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001887 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001888 }
1889 return false;
1890}
1891
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001892void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001893 int32_t keyEventAction, int32_t keyEventFlags) {
1894 int32_t keyCode = mCurrentVirtualKey.keyCode;
1895 int32_t scanCode = mCurrentVirtualKey.scanCode;
1896 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001897 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001898 policyFlags |= POLICY_FLAG_VIRTUAL;
1899
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001900 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1901 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1902 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001903 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001904}
1905
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001906void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1908 if (!currentIdBits.isEmpty()) {
1909 int32_t metaState = getContext()->getGlobalMetaState();
1910 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001911 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1912 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001913 mCurrentCookedState.cookedPointerData.pointerProperties,
1914 mCurrentCookedState.cookedPointerData.pointerCoords,
1915 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1916 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1917 mCurrentMotionAborted = true;
1918 }
1919}
1920
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001921void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001922 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1923 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1924 int32_t metaState = getContext()->getGlobalMetaState();
1925 int32_t buttonState = mCurrentCookedState.buttonState;
1926
1927 if (currentIdBits == lastIdBits) {
1928 if (!currentIdBits.isEmpty()) {
1929 // No pointer id changes so this is a move event.
1930 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001931 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1932 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001933 mCurrentCookedState.cookedPointerData.pointerProperties,
1934 mCurrentCookedState.cookedPointerData.pointerCoords,
1935 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1936 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1937 }
1938 } else {
1939 // There may be pointers going up and pointers going down and pointers moving
1940 // all at the same time.
1941 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1942 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1943 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1944 BitSet32 dispatchedIdBits(lastIdBits.value);
1945
1946 // Update last coordinates of pointers that have moved so that we observe the new
1947 // pointer positions at the same time as other pointers that have just gone up.
1948 bool moveNeeded =
1949 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1950 mCurrentCookedState.cookedPointerData.pointerCoords,
1951 mCurrentCookedState.cookedPointerData.idToIndex,
1952 mLastCookedState.cookedPointerData.pointerProperties,
1953 mLastCookedState.cookedPointerData.pointerCoords,
1954 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1955 if (buttonState != mLastCookedState.buttonState) {
1956 moveNeeded = true;
1957 }
1958
1959 // Dispatch pointer up events.
1960 while (!upIdBits.isEmpty()) {
1961 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001962 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001963 if (isCanceled) {
1964 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1965 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001966 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001967 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001968 mLastCookedState.cookedPointerData.pointerProperties,
1969 mLastCookedState.cookedPointerData.pointerCoords,
1970 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1971 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1972 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001973 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001974 }
1975
1976 // Dispatch move events if any of the remaining pointers moved from their old locations.
1977 // Although applications receive new locations as part of individual pointer up
1978 // events, they do not generally handle them except when presented in a move event.
1979 if (moveNeeded && !moveIdBits.isEmpty()) {
1980 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001981 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1982 metaState, buttonState, 0,
1983 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001984 mCurrentCookedState.cookedPointerData.pointerCoords,
1985 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1986 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1987 }
1988
1989 // Dispatch pointer down events using the new pointer locations.
1990 while (!downIdBits.isEmpty()) {
1991 uint32_t downId = downIdBits.clearFirstMarkedBit();
1992 dispatchedIdBits.markBit(downId);
1993
1994 if (dispatchedIdBits.count() == 1) {
1995 // First pointer is going down. Set down time.
1996 mDownTime = when;
1997 }
1998
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001999 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2000 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002001 mCurrentCookedState.cookedPointerData.pointerProperties,
2002 mCurrentCookedState.cookedPointerData.pointerCoords,
2003 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
2004 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2005 }
2006 }
2007}
2008
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002009void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002010 if (mSentHoverEnter &&
2011 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2012 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2013 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002014 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2015 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002016 mLastCookedState.cookedPointerData.pointerProperties,
2017 mLastCookedState.cookedPointerData.pointerCoords,
2018 mLastCookedState.cookedPointerData.idToIndex,
2019 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2020 mOrientedYPrecision, mDownTime);
2021 mSentHoverEnter = false;
2022 }
2023}
2024
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002025void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2026 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002027 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2028 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2029 int32_t metaState = getContext()->getGlobalMetaState();
2030 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002031 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2032 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002033 mCurrentCookedState.cookedPointerData.pointerProperties,
2034 mCurrentCookedState.cookedPointerData.pointerCoords,
2035 mCurrentCookedState.cookedPointerData.idToIndex,
2036 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2037 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2038 mSentHoverEnter = true;
2039 }
2040
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002041 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2042 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002043 mCurrentCookedState.cookedPointerData.pointerProperties,
2044 mCurrentCookedState.cookedPointerData.pointerCoords,
2045 mCurrentCookedState.cookedPointerData.idToIndex,
2046 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2047 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2048 }
2049}
2050
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002051void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002052 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2053 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2054 const int32_t metaState = getContext()->getGlobalMetaState();
2055 int32_t buttonState = mLastCookedState.buttonState;
2056 while (!releasedButtons.isEmpty()) {
2057 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2058 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002059 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002060 actionButton, 0, metaState, buttonState, 0,
2061 mCurrentCookedState.cookedPointerData.pointerProperties,
2062 mCurrentCookedState.cookedPointerData.pointerCoords,
2063 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2064 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2065 }
2066}
2067
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002068void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002069 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2070 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2071 const int32_t metaState = getContext()->getGlobalMetaState();
2072 int32_t buttonState = mLastCookedState.buttonState;
2073 while (!pressedButtons.isEmpty()) {
2074 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2075 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002076 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2077 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002078 mCurrentCookedState.cookedPointerData.pointerProperties,
2079 mCurrentCookedState.cookedPointerData.pointerCoords,
2080 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2081 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2082 }
2083}
2084
2085const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2086 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2087 return cookedPointerData.touchingIdBits;
2088 }
2089 return cookedPointerData.hoveringIdBits;
2090}
2091
2092void TouchInputMapper::cookPointerData() {
2093 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2094
2095 mCurrentCookedState.cookedPointerData.clear();
2096 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2097 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2098 mCurrentRawState.rawPointerData.hoveringIdBits;
2099 mCurrentCookedState.cookedPointerData.touchingIdBits =
2100 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002101 mCurrentCookedState.cookedPointerData.canceledIdBits =
2102 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002103
2104 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2105 mCurrentCookedState.buttonState = 0;
2106 } else {
2107 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2108 }
2109
2110 // Walk through the the active pointers and map device coordinates onto
2111 // surface coordinates and adjust for display orientation.
2112 for (uint32_t i = 0; i < currentPointerCount; i++) {
2113 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2114
2115 // Size
2116 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2117 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002118 case Calibration::SizeCalibration::GEOMETRIC:
2119 case Calibration::SizeCalibration::DIAMETER:
2120 case Calibration::SizeCalibration::BOX:
2121 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002122 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2123 touchMajor = in.touchMajor;
2124 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2125 toolMajor = in.toolMajor;
2126 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2127 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2128 : in.touchMajor;
2129 } else if (mRawPointerAxes.touchMajor.valid) {
2130 toolMajor = touchMajor = in.touchMajor;
2131 toolMinor = touchMinor =
2132 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2133 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2134 : in.touchMajor;
2135 } else if (mRawPointerAxes.toolMajor.valid) {
2136 touchMajor = toolMajor = in.toolMajor;
2137 touchMinor = toolMinor =
2138 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2139 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2140 : in.toolMajor;
2141 } else {
2142 ALOG_ASSERT(false,
2143 "No touch or tool axes. "
2144 "Size calibration should have been resolved to NONE.");
2145 touchMajor = 0;
2146 touchMinor = 0;
2147 toolMajor = 0;
2148 toolMinor = 0;
2149 size = 0;
2150 }
2151
2152 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2153 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2154 if (touchingCount > 1) {
2155 touchMajor /= touchingCount;
2156 touchMinor /= touchingCount;
2157 toolMajor /= touchingCount;
2158 toolMinor /= touchingCount;
2159 size /= touchingCount;
2160 }
2161 }
2162
Michael Wright227c5542020-07-02 18:30:52 +01002163 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002164 touchMajor *= mGeometricScale;
2165 touchMinor *= mGeometricScale;
2166 toolMajor *= mGeometricScale;
2167 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002168 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002169 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2170 touchMinor = touchMajor;
2171 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2172 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002173 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002174 touchMinor = touchMajor;
2175 toolMinor = toolMajor;
2176 }
2177
2178 mCalibration.applySizeScaleAndBias(&touchMajor);
2179 mCalibration.applySizeScaleAndBias(&touchMinor);
2180 mCalibration.applySizeScaleAndBias(&toolMajor);
2181 mCalibration.applySizeScaleAndBias(&toolMinor);
2182 size *= mSizeScale;
2183 break;
2184 default:
2185 touchMajor = 0;
2186 touchMinor = 0;
2187 toolMajor = 0;
2188 toolMinor = 0;
2189 size = 0;
2190 break;
2191 }
2192
2193 // Pressure
2194 float pressure;
2195 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002196 case Calibration::PressureCalibration::PHYSICAL:
2197 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002198 pressure = in.pressure * mPressureScale;
2199 break;
2200 default:
2201 pressure = in.isHovering ? 0 : 1;
2202 break;
2203 }
2204
2205 // Tilt and Orientation
2206 float tilt;
2207 float orientation;
2208 if (mHaveTilt) {
2209 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2210 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2211 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2212 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2213 } else {
2214 tilt = 0;
2215
2216 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002217 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002218 orientation = in.orientation * mOrientationScale;
2219 break;
Michael Wright227c5542020-07-02 18:30:52 +01002220 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002221 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2222 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2223 if (c1 != 0 || c2 != 0) {
2224 orientation = atan2f(c1, c2) * 0.5f;
2225 float confidence = hypotf(c1, c2);
2226 float scale = 1.0f + confidence / 16.0f;
2227 touchMajor *= scale;
2228 touchMinor /= scale;
2229 toolMajor *= scale;
2230 toolMinor /= scale;
2231 } else {
2232 orientation = 0;
2233 }
2234 break;
2235 }
2236 default:
2237 orientation = 0;
2238 }
2239 }
2240
2241 // Distance
2242 float distance;
2243 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002244 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002245 distance = in.distance * mDistanceScale;
2246 break;
2247 default:
2248 distance = 0;
2249 }
2250
2251 // Coverage
2252 int32_t rawLeft, rawTop, rawRight, rawBottom;
2253 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002254 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002255 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2256 rawRight = in.toolMinor & 0x0000ffff;
2257 rawBottom = in.toolMajor & 0x0000ffff;
2258 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2259 break;
2260 default:
2261 rawLeft = rawTop = rawRight = rawBottom = 0;
2262 break;
2263 }
2264
2265 // Adjust X,Y coords for device calibration
2266 // TODO: Adjust coverage coords?
2267 float xTransformed = in.x, yTransformed = in.y;
2268 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002269 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002270
2271 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002272 float left, top, right, bottom;
2273
2274 switch (mSurfaceOrientation) {
2275 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002276 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2277 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2278 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2279 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2280 orientation -= M_PI_2;
2281 if (mOrientedRanges.haveOrientation &&
2282 orientation < mOrientedRanges.orientation.min) {
2283 orientation +=
2284 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2285 }
2286 break;
2287 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002288 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2289 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2290 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2291 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2292 orientation -= M_PI;
2293 if (mOrientedRanges.haveOrientation &&
2294 orientation < mOrientedRanges.orientation.min) {
2295 orientation +=
2296 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2297 }
2298 break;
2299 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002300 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2301 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2302 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2303 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2304 orientation += M_PI_2;
2305 if (mOrientedRanges.haveOrientation &&
2306 orientation > mOrientedRanges.orientation.max) {
2307 orientation -=
2308 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2309 }
2310 break;
2311 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002312 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2313 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2314 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2315 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2316 break;
2317 }
2318
2319 // Write output coords.
2320 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2321 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002322 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2323 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002324 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2325 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2326 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2327 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2328 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2329 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2330 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002331 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2333 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2334 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2335 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2336 } else {
2337 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2338 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2339 }
2340
Chris Ye364fdb52020-08-05 15:07:56 -07002341 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002342 uint32_t id = in.id;
2343 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2344 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2345 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2346 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2347 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2348 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2349 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2350 }
2351
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 // Write output properties.
2353 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 properties.clear();
2355 properties.id = id;
2356 properties.toolType = in.toolType;
2357
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002358 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002360 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 }
2362}
2363
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002364void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 PointerUsage pointerUsage) {
2366 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002367 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 mPointerUsage = pointerUsage;
2369 }
2370
2371 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002372 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002373 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 break;
Michael Wright227c5542020-07-02 18:30:52 +01002375 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002376 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 break;
Michael Wright227c5542020-07-02 18:30:52 +01002378 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002379 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 break;
Michael Wright227c5542020-07-02 18:30:52 +01002381 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 break;
2383 }
2384}
2385
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002386void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002388 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002389 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 break;
Michael Wright227c5542020-07-02 18:30:52 +01002391 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002392 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393 break;
Michael Wright227c5542020-07-02 18:30:52 +01002394 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002395 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 break;
Michael Wright227c5542020-07-02 18:30:52 +01002397 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 break;
2399 }
2400
Michael Wright227c5542020-07-02 18:30:52 +01002401 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402}
2403
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002404void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2405 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 // Update current gesture coordinates.
2407 bool cancelPreviousGesture, finishPreviousGesture;
2408 bool sendEvents =
2409 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2410 if (!sendEvents) {
2411 return;
2412 }
2413 if (finishPreviousGesture) {
2414 cancelPreviousGesture = false;
2415 }
2416
2417 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002418 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002419 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 if (finishPreviousGesture || cancelPreviousGesture) {
2421 mPointerController->clearSpots();
2422 }
2423
Michael Wright227c5542020-07-02 18:30:52 +01002424 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002425 setTouchSpots(mPointerGesture.currentGestureCoords,
2426 mPointerGesture.currentGestureIdToIndex,
2427 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002428 }
2429 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002430 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431 }
2432
2433 // Show or hide the pointer if needed.
2434 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002435 case PointerGesture::Mode::NEUTRAL:
2436 case PointerGesture::Mode::QUIET:
2437 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2438 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002439 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002440 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002441 }
2442 break;
Michael Wright227c5542020-07-02 18:30:52 +01002443 case PointerGesture::Mode::TAP:
2444 case PointerGesture::Mode::TAP_DRAG:
2445 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2446 case PointerGesture::Mode::HOVER:
2447 case PointerGesture::Mode::PRESS:
2448 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002449 // Unfade the pointer when the current gesture manipulates the
2450 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002451 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452 break;
Michael Wright227c5542020-07-02 18:30:52 +01002453 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454 // Fade the pointer when the current gesture manipulates a different
2455 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002456 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002457 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002459 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 }
2461 break;
2462 }
2463
2464 // Send events!
2465 int32_t metaState = getContext()->getGlobalMetaState();
2466 int32_t buttonState = mCurrentCookedState.buttonState;
2467
2468 // Update last coordinates of pointers that have moved so that we observe the new
2469 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002470 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2471 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2472 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2473 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2474 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2475 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476 bool moveNeeded = false;
2477 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2478 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2479 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2480 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2481 mPointerGesture.lastGestureIdBits.value);
2482 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2483 mPointerGesture.currentGestureCoords,
2484 mPointerGesture.currentGestureIdToIndex,
2485 mPointerGesture.lastGestureProperties,
2486 mPointerGesture.lastGestureCoords,
2487 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2488 if (buttonState != mLastCookedState.buttonState) {
2489 moveNeeded = true;
2490 }
2491 }
2492
2493 // Send motion events for all pointers that went up or were canceled.
2494 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2495 if (!dispatchedGestureIdBits.isEmpty()) {
2496 if (cancelPreviousGesture) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002497 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2498 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002499 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2500 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2501 mPointerGesture.downTime);
2502
2503 dispatchedGestureIdBits.clear();
2504 } else {
2505 BitSet32 upGestureIdBits;
2506 if (finishPreviousGesture) {
2507 upGestureIdBits = dispatchedGestureIdBits;
2508 } else {
2509 upGestureIdBits.value =
2510 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2511 }
2512 while (!upGestureIdBits.isEmpty()) {
2513 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2514
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002515 dispatchMotion(when, readTime, policyFlags, mSource,
2516 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState,
2517 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002518 mPointerGesture.lastGestureCoords,
2519 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2520 0, mPointerGesture.downTime);
2521
2522 dispatchedGestureIdBits.clearBit(id);
2523 }
2524 }
2525 }
2526
2527 // Send motion events for all pointers that moved.
2528 if (moveNeeded) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002529 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
2530 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002531 mPointerGesture.currentGestureProperties,
2532 mPointerGesture.currentGestureCoords,
2533 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2534 mPointerGesture.downTime);
2535 }
2536
2537 // Send motion events for all pointers that went down.
2538 if (down) {
2539 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2540 ~dispatchedGestureIdBits.value);
2541 while (!downGestureIdBits.isEmpty()) {
2542 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2543 dispatchedGestureIdBits.markBit(id);
2544
2545 if (dispatchedGestureIdBits.count() == 1) {
2546 mPointerGesture.downTime = when;
2547 }
2548
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002549 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2550 0, 0, metaState, buttonState, 0,
2551 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552 mPointerGesture.currentGestureCoords,
2553 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2554 0, mPointerGesture.downTime);
2555 }
2556 }
2557
2558 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002559 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002560 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2561 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002562 mPointerGesture.currentGestureProperties,
2563 mPointerGesture.currentGestureCoords,
2564 mPointerGesture.currentGestureIdToIndex,
2565 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2566 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2567 // Synthesize a hover move event after all pointers go up to indicate that
2568 // the pointer is hovering again even if the user is not currently touching
2569 // the touch pad. This ensures that a view will receive a fresh hover enter
2570 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002571 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002572
2573 PointerProperties pointerProperties;
2574 pointerProperties.clear();
2575 pointerProperties.id = 0;
2576 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2577
2578 PointerCoords pointerCoords;
2579 pointerCoords.clear();
2580 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2581 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2582
2583 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002584 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
2585 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2586 metaState, buttonState, MotionClassification::NONE,
2587 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2588 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002589 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002590 }
2591
2592 // Update state.
2593 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2594 if (!down) {
2595 mPointerGesture.lastGestureIdBits.clear();
2596 } else {
2597 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2598 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2599 uint32_t id = idBits.clearFirstMarkedBit();
2600 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2601 mPointerGesture.lastGestureProperties[index].copyFrom(
2602 mPointerGesture.currentGestureProperties[index]);
2603 mPointerGesture.lastGestureCoords[index].copyFrom(
2604 mPointerGesture.currentGestureCoords[index]);
2605 mPointerGesture.lastGestureIdToIndex[id] = index;
2606 }
2607 }
2608}
2609
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002610void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002611 // Cancel previously dispatches pointers.
2612 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2613 int32_t metaState = getContext()->getGlobalMetaState();
2614 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002615 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2616 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002617 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2618 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2619 0, 0, mPointerGesture.downTime);
2620 }
2621
2622 // Reset the current pointer gesture.
2623 mPointerGesture.reset();
2624 mPointerVelocityControl.reset();
2625
2626 // Remove any current spots.
2627 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002628 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002629 mPointerController->clearSpots();
2630 }
2631}
2632
2633bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2634 bool* outFinishPreviousGesture, bool isTimeout) {
2635 *outCancelPreviousGesture = false;
2636 *outFinishPreviousGesture = false;
2637
2638 // Handle TAP timeout.
2639 if (isTimeout) {
2640#if DEBUG_GESTURES
2641 ALOGD("Gestures: Processing timeout");
2642#endif
2643
Michael Wright227c5542020-07-02 18:30:52 +01002644 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002645 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2646 // The tap/drag timeout has not yet expired.
2647 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2648 mConfig.pointerGestureTapDragInterval);
2649 } else {
2650 // The tap is finished.
2651#if DEBUG_GESTURES
2652 ALOGD("Gestures: TAP finished");
2653#endif
2654 *outFinishPreviousGesture = true;
2655
2656 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002657 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002658 mPointerGesture.currentGestureIdBits.clear();
2659
2660 mPointerVelocityControl.reset();
2661 return true;
2662 }
2663 }
2664
2665 // We did not handle this timeout.
2666 return false;
2667 }
2668
2669 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2670 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2671
2672 // Update the velocity tracker.
2673 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002674 std::vector<VelocityTracker::Position> positions;
2675 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002676 uint32_t id = idBits.clearFirstMarkedBit();
2677 const RawPointerData::Pointer& pointer =
2678 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002679 float x = pointer.x * mPointerXMovementScale;
2680 float y = pointer.y * mPointerYMovementScale;
2681 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002682 }
2683 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2684 positions);
2685 }
2686
2687 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2688 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002689 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2690 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2691 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002692 mPointerGesture.resetTap();
2693 }
2694
2695 // Pick a new active touch id if needed.
2696 // Choose an arbitrary pointer that just went down, if there is one.
2697 // Otherwise choose an arbitrary remaining pointer.
2698 // This guarantees we always have an active touch id when there is at least one pointer.
2699 // We keep the same active touch id for as long as possible.
2700 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2701 int32_t activeTouchId = lastActiveTouchId;
2702 if (activeTouchId < 0) {
2703 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2704 activeTouchId = mPointerGesture.activeTouchId =
2705 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2706 mPointerGesture.firstTouchTime = when;
2707 }
2708 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2709 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2710 activeTouchId = mPointerGesture.activeTouchId =
2711 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2712 } else {
2713 activeTouchId = mPointerGesture.activeTouchId = -1;
2714 }
2715 }
2716
2717 // Determine whether we are in quiet time.
2718 bool isQuietTime = false;
2719 if (activeTouchId < 0) {
2720 mPointerGesture.resetQuietTime();
2721 } else {
2722 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2723 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002724 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2725 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2726 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002727 currentFingerCount < 2) {
2728 // Enter quiet time when exiting swipe or freeform state.
2729 // This is to prevent accidentally entering the hover state and flinging the
2730 // pointer when finishing a swipe and there is still one pointer left onscreen.
2731 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002732 } else if (mPointerGesture.lastGestureMode ==
2733 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002734 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2735 // Enter quiet time when releasing the button and there are still two or more
2736 // fingers down. This may indicate that one finger was used to press the button
2737 // but it has not gone up yet.
2738 isQuietTime = true;
2739 }
2740 if (isQuietTime) {
2741 mPointerGesture.quietTime = when;
2742 }
2743 }
2744 }
2745
2746 // Switch states based on button and pointer state.
2747 if (isQuietTime) {
2748 // Case 1: Quiet time. (QUIET)
2749#if DEBUG_GESTURES
2750 ALOGD("Gestures: QUIET for next %0.3fms",
2751 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2752#endif
Michael Wright227c5542020-07-02 18:30:52 +01002753 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002754 *outFinishPreviousGesture = true;
2755 }
2756
2757 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002758 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002759 mPointerGesture.currentGestureIdBits.clear();
2760
2761 mPointerVelocityControl.reset();
2762 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2763 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2764 // The pointer follows the active touch point.
2765 // Emit DOWN, MOVE, UP events at the pointer location.
2766 //
2767 // Only the active touch matters; other fingers are ignored. This policy helps
2768 // to handle the case where the user places a second finger on the touch pad
2769 // to apply the necessary force to depress an integrated button below the surface.
2770 // We don't want the second finger to be delivered to applications.
2771 //
2772 // For this to work well, we need to make sure to track the pointer that is really
2773 // active. If the user first puts one finger down to click then adds another
2774 // finger to drag then the active pointer should switch to the finger that is
2775 // being dragged.
2776#if DEBUG_GESTURES
2777 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2778 "currentFingerCount=%d",
2779 activeTouchId, currentFingerCount);
2780#endif
2781 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002782 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002783 *outFinishPreviousGesture = true;
2784 mPointerGesture.activeGestureId = 0;
2785 }
2786
2787 // Switch pointers if needed.
2788 // Find the fastest pointer and follow it.
2789 if (activeTouchId >= 0 && currentFingerCount > 1) {
2790 int32_t bestId = -1;
2791 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2792 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2793 uint32_t id = idBits.clearFirstMarkedBit();
2794 float vx, vy;
2795 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2796 float speed = hypotf(vx, vy);
2797 if (speed > bestSpeed) {
2798 bestId = id;
2799 bestSpeed = speed;
2800 }
2801 }
2802 }
2803 if (bestId >= 0 && bestId != activeTouchId) {
2804 mPointerGesture.activeTouchId = activeTouchId = bestId;
2805#if DEBUG_GESTURES
2806 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2807 "bestId=%d, bestSpeed=%0.3f",
2808 bestId, bestSpeed);
2809#endif
2810 }
2811 }
2812
2813 float deltaX = 0, deltaY = 0;
2814 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2815 const RawPointerData::Pointer& currentPointer =
2816 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2817 const RawPointerData::Pointer& lastPointer =
2818 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2819 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2820 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2821
2822 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2823 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2824
2825 // Move the pointer using a relative motion.
2826 // When using spots, the click will occur at the position of the anchor
2827 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002828 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002829 } else {
2830 mPointerVelocityControl.reset();
2831 }
2832
Prabir Pradhand7482e72021-03-09 13:54:55 -08002833 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002834
Michael Wright227c5542020-07-02 18:30:52 +01002835 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002836 mPointerGesture.currentGestureIdBits.clear();
2837 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2838 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2839 mPointerGesture.currentGestureProperties[0].clear();
2840 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2841 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2842 mPointerGesture.currentGestureCoords[0].clear();
2843 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2844 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2845 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2846 } else if (currentFingerCount == 0) {
2847 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002848 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 *outFinishPreviousGesture = true;
2850 }
2851
2852 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2853 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2854 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002855 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2856 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857 lastFingerCount == 1) {
2858 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002859 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002860 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2861 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2862#if DEBUG_GESTURES
2863 ALOGD("Gestures: TAP");
2864#endif
2865
2866 mPointerGesture.tapUpTime = when;
2867 getContext()->requestTimeoutAtTime(when +
2868 mConfig.pointerGestureTapDragInterval);
2869
2870 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002871 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 mPointerGesture.currentGestureIdBits.clear();
2873 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2874 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2875 mPointerGesture.currentGestureProperties[0].clear();
2876 mPointerGesture.currentGestureProperties[0].id =
2877 mPointerGesture.activeGestureId;
2878 mPointerGesture.currentGestureProperties[0].toolType =
2879 AMOTION_EVENT_TOOL_TYPE_FINGER;
2880 mPointerGesture.currentGestureCoords[0].clear();
2881 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2882 mPointerGesture.tapX);
2883 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2884 mPointerGesture.tapY);
2885 mPointerGesture.currentGestureCoords[0]
2886 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2887
2888 tapped = true;
2889 } else {
2890#if DEBUG_GESTURES
2891 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2892 y - mPointerGesture.tapY);
2893#endif
2894 }
2895 } else {
2896#if DEBUG_GESTURES
2897 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2898 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2899 (when - mPointerGesture.tapDownTime) * 0.000001f);
2900 } else {
2901 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2902 }
2903#endif
2904 }
2905 }
2906
2907 mPointerVelocityControl.reset();
2908
2909 if (!tapped) {
2910#if DEBUG_GESTURES
2911 ALOGD("Gestures: NEUTRAL");
2912#endif
2913 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002914 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002915 mPointerGesture.currentGestureIdBits.clear();
2916 }
2917 } else if (currentFingerCount == 1) {
2918 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2919 // The pointer follows the active touch point.
2920 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2921 // When in TAP_DRAG, emit MOVE events at the pointer location.
2922 ALOG_ASSERT(activeTouchId >= 0);
2923
Michael Wright227c5542020-07-02 18:30:52 +01002924 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2925 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002926 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002927 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002928 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2929 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002930 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002931 } else {
2932#if DEBUG_GESTURES
2933 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2934 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2935#endif
2936 }
2937 } else {
2938#if DEBUG_GESTURES
2939 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2940 (when - mPointerGesture.tapUpTime) * 0.000001f);
2941#endif
2942 }
Michael Wright227c5542020-07-02 18:30:52 +01002943 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2944 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 }
2946
2947 float deltaX = 0, deltaY = 0;
2948 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2949 const RawPointerData::Pointer& currentPointer =
2950 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2951 const RawPointerData::Pointer& lastPointer =
2952 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2953 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2954 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2955
2956 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2957 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2958
2959 // Move the pointer using a relative motion.
2960 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002961 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002962 } else {
2963 mPointerVelocityControl.reset();
2964 }
2965
2966 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002967 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968#if DEBUG_GESTURES
2969 ALOGD("Gestures: TAP_DRAG");
2970#endif
2971 down = true;
2972 } else {
2973#if DEBUG_GESTURES
2974 ALOGD("Gestures: HOVER");
2975#endif
Michael Wright227c5542020-07-02 18:30:52 +01002976 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002977 *outFinishPreviousGesture = true;
2978 }
2979 mPointerGesture.activeGestureId = 0;
2980 down = false;
2981 }
2982
Prabir Pradhand7482e72021-03-09 13:54:55 -08002983 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984
2985 mPointerGesture.currentGestureIdBits.clear();
2986 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2987 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2988 mPointerGesture.currentGestureProperties[0].clear();
2989 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2990 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2991 mPointerGesture.currentGestureCoords[0].clear();
2992 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2993 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2994 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2995 down ? 1.0f : 0.0f);
2996
2997 if (lastFingerCount == 0 && currentFingerCount != 0) {
2998 mPointerGesture.resetTap();
2999 mPointerGesture.tapDownTime = when;
3000 mPointerGesture.tapX = x;
3001 mPointerGesture.tapY = y;
3002 }
3003 } else {
3004 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3005 // We need to provide feedback for each finger that goes down so we cannot wait
3006 // for the fingers to move before deciding what to do.
3007 //
3008 // The ambiguous case is deciding what to do when there are two fingers down but they
3009 // have not moved enough to determine whether they are part of a drag or part of a
3010 // freeform gesture, or just a press or long-press at the pointer location.
3011 //
3012 // When there are two fingers we start with the PRESS hypothesis and we generate a
3013 // down at the pointer location.
3014 //
3015 // When the two fingers move enough or when additional fingers are added, we make
3016 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3017 ALOG_ASSERT(activeTouchId >= 0);
3018
3019 bool settled = when >=
3020 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003021 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3022 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3023 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003024 *outFinishPreviousGesture = true;
3025 } else if (!settled && currentFingerCount > lastFingerCount) {
3026 // Additional pointers have gone down but not yet settled.
3027 // Reset the gesture.
3028#if DEBUG_GESTURES
3029 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3030 "settle time remaining %0.3fms",
3031 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3032 when) * 0.000001f);
3033#endif
3034 *outCancelPreviousGesture = true;
3035 } else {
3036 // Continue previous gesture.
3037 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3038 }
3039
3040 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003041 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003042 mPointerGesture.activeGestureId = 0;
3043 mPointerGesture.referenceIdBits.clear();
3044 mPointerVelocityControl.reset();
3045
3046 // Use the centroid and pointer location as the reference points for the gesture.
3047#if DEBUG_GESTURES
3048 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3049 "settle time remaining %0.3fms",
3050 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3051 when) * 0.000001f);
3052#endif
3053 mCurrentRawState.rawPointerData
3054 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3055 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003056 auto [x, y] = getMouseCursorPosition();
3057 mPointerGesture.referenceGestureX = x;
3058 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003059 }
3060
3061 // Clear the reference deltas for fingers not yet included in the reference calculation.
3062 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3063 ~mPointerGesture.referenceIdBits.value);
3064 !idBits.isEmpty();) {
3065 uint32_t id = idBits.clearFirstMarkedBit();
3066 mPointerGesture.referenceDeltas[id].dx = 0;
3067 mPointerGesture.referenceDeltas[id].dy = 0;
3068 }
3069 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3070
3071 // Add delta for all fingers and calculate a common movement delta.
3072 float commonDeltaX = 0, commonDeltaY = 0;
3073 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3074 mCurrentCookedState.fingerIdBits.value);
3075 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3076 bool first = (idBits == commonIdBits);
3077 uint32_t id = idBits.clearFirstMarkedBit();
3078 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3079 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3080 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3081 delta.dx += cpd.x - lpd.x;
3082 delta.dy += cpd.y - lpd.y;
3083
3084 if (first) {
3085 commonDeltaX = delta.dx;
3086 commonDeltaY = delta.dy;
3087 } else {
3088 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3089 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3090 }
3091 }
3092
3093 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003094 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003095 float dist[MAX_POINTER_ID + 1];
3096 int32_t distOverThreshold = 0;
3097 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3098 uint32_t id = idBits.clearFirstMarkedBit();
3099 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3100 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3101 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3102 distOverThreshold += 1;
3103 }
3104 }
3105
3106 // Only transition when at least two pointers have moved further than
3107 // the minimum distance threshold.
3108 if (distOverThreshold >= 2) {
3109 if (currentFingerCount > 2) {
3110 // There are more than two pointers, switch to FREEFORM.
3111#if DEBUG_GESTURES
3112 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3113 currentFingerCount);
3114#endif
3115 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003116 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003117 } else {
3118 // There are exactly two pointers.
3119 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3120 uint32_t id1 = idBits.clearFirstMarkedBit();
3121 uint32_t id2 = idBits.firstMarkedBit();
3122 const RawPointerData::Pointer& p1 =
3123 mCurrentRawState.rawPointerData.pointerForId(id1);
3124 const RawPointerData::Pointer& p2 =
3125 mCurrentRawState.rawPointerData.pointerForId(id2);
3126 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3127 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3128 // There are two pointers but they are too far apart for a SWIPE,
3129 // switch to FREEFORM.
3130#if DEBUG_GESTURES
3131 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3132 mutualDistance, mPointerGestureMaxSwipeWidth);
3133#endif
3134 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003135 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003136 } else {
3137 // There are two pointers. Wait for both pointers to start moving
3138 // before deciding whether this is a SWIPE or FREEFORM gesture.
3139 float dist1 = dist[id1];
3140 float dist2 = dist[id2];
3141 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3142 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3143 // Calculate the dot product of the displacement vectors.
3144 // When the vectors are oriented in approximately the same direction,
3145 // the angle betweeen them is near zero and the cosine of the angle
3146 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3147 // mag(v2).
3148 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3149 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3150 float dx1 = delta1.dx * mPointerXZoomScale;
3151 float dy1 = delta1.dy * mPointerYZoomScale;
3152 float dx2 = delta2.dx * mPointerXZoomScale;
3153 float dy2 = delta2.dy * mPointerYZoomScale;
3154 float dot = dx1 * dx2 + dy1 * dy2;
3155 float cosine = dot / (dist1 * dist2); // denominator always > 0
3156 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3157 // Pointers are moving in the same direction. Switch to SWIPE.
3158#if DEBUG_GESTURES
3159 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3160 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3161 "cosine %0.3f >= %0.3f",
3162 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3163 mConfig.pointerGestureMultitouchMinDistance, cosine,
3164 mConfig.pointerGestureSwipeTransitionAngleCosine);
3165#endif
Michael Wright227c5542020-07-02 18:30:52 +01003166 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003167 } else {
3168 // Pointers are moving in different directions. Switch to FREEFORM.
3169#if DEBUG_GESTURES
3170 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3171 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3172 "cosine %0.3f < %0.3f",
3173 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3174 mConfig.pointerGestureMultitouchMinDistance, cosine,
3175 mConfig.pointerGestureSwipeTransitionAngleCosine);
3176#endif
3177 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003178 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003179 }
3180 }
3181 }
3182 }
3183 }
Michael Wright227c5542020-07-02 18:30:52 +01003184 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003185 // Switch from SWIPE to FREEFORM if additional pointers go down.
3186 // Cancel previous gesture.
3187 if (currentFingerCount > 2) {
3188#if DEBUG_GESTURES
3189 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3190 currentFingerCount);
3191#endif
3192 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003193 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003194 }
3195 }
3196
3197 // Move the reference points based on the overall group motion of the fingers
3198 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003199 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003200 (commonDeltaX || commonDeltaY)) {
3201 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3202 uint32_t id = idBits.clearFirstMarkedBit();
3203 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3204 delta.dx = 0;
3205 delta.dy = 0;
3206 }
3207
3208 mPointerGesture.referenceTouchX += commonDeltaX;
3209 mPointerGesture.referenceTouchY += commonDeltaY;
3210
3211 commonDeltaX *= mPointerXMovementScale;
3212 commonDeltaY *= mPointerYMovementScale;
3213
3214 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3215 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3216
3217 mPointerGesture.referenceGestureX += commonDeltaX;
3218 mPointerGesture.referenceGestureY += commonDeltaY;
3219 }
3220
3221 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003222 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3223 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003224 // PRESS or SWIPE mode.
3225#if DEBUG_GESTURES
3226 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3227 "activeGestureId=%d, currentTouchPointerCount=%d",
3228 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3229#endif
3230 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3231
3232 mPointerGesture.currentGestureIdBits.clear();
3233 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3234 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3235 mPointerGesture.currentGestureProperties[0].clear();
3236 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3237 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3238 mPointerGesture.currentGestureCoords[0].clear();
3239 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3240 mPointerGesture.referenceGestureX);
3241 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3242 mPointerGesture.referenceGestureY);
3243 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003244 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003245 // FREEFORM mode.
3246#if DEBUG_GESTURES
3247 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3248 "activeGestureId=%d, currentTouchPointerCount=%d",
3249 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3250#endif
3251 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3252
3253 mPointerGesture.currentGestureIdBits.clear();
3254
3255 BitSet32 mappedTouchIdBits;
3256 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003257 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003258 // Initially, assign the active gesture id to the active touch point
3259 // if there is one. No other touch id bits are mapped yet.
3260 if (!*outCancelPreviousGesture) {
3261 mappedTouchIdBits.markBit(activeTouchId);
3262 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3263 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3264 mPointerGesture.activeGestureId;
3265 } else {
3266 mPointerGesture.activeGestureId = -1;
3267 }
3268 } else {
3269 // Otherwise, assume we mapped all touches from the previous frame.
3270 // Reuse all mappings that are still applicable.
3271 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3272 mCurrentCookedState.fingerIdBits.value;
3273 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3274
3275 // Check whether we need to choose a new active gesture id because the
3276 // current went went up.
3277 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3278 ~mCurrentCookedState.fingerIdBits.value);
3279 !upTouchIdBits.isEmpty();) {
3280 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3281 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3282 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3283 mPointerGesture.activeGestureId = -1;
3284 break;
3285 }
3286 }
3287 }
3288
3289#if DEBUG_GESTURES
3290 ALOGD("Gestures: FREEFORM follow up "
3291 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3292 "activeGestureId=%d",
3293 mappedTouchIdBits.value, usedGestureIdBits.value,
3294 mPointerGesture.activeGestureId);
3295#endif
3296
3297 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3298 for (uint32_t i = 0; i < currentFingerCount; i++) {
3299 uint32_t touchId = idBits.clearFirstMarkedBit();
3300 uint32_t gestureId;
3301 if (!mappedTouchIdBits.hasBit(touchId)) {
3302 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3303 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3304#if DEBUG_GESTURES
3305 ALOGD("Gestures: FREEFORM "
3306 "new mapping for touch id %d -> gesture id %d",
3307 touchId, gestureId);
3308#endif
3309 } else {
3310 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3311#if DEBUG_GESTURES
3312 ALOGD("Gestures: FREEFORM "
3313 "existing mapping for touch id %d -> gesture id %d",
3314 touchId, gestureId);
3315#endif
3316 }
3317 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3318 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3319
3320 const RawPointerData::Pointer& pointer =
3321 mCurrentRawState.rawPointerData.pointerForId(touchId);
3322 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3323 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3324 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3325
3326 mPointerGesture.currentGestureProperties[i].clear();
3327 mPointerGesture.currentGestureProperties[i].id = gestureId;
3328 mPointerGesture.currentGestureProperties[i].toolType =
3329 AMOTION_EVENT_TOOL_TYPE_FINGER;
3330 mPointerGesture.currentGestureCoords[i].clear();
3331 mPointerGesture.currentGestureCoords[i]
3332 .setAxisValue(AMOTION_EVENT_AXIS_X,
3333 mPointerGesture.referenceGestureX + deltaX);
3334 mPointerGesture.currentGestureCoords[i]
3335 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3336 mPointerGesture.referenceGestureY + deltaY);
3337 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3338 1.0f);
3339 }
3340
3341 if (mPointerGesture.activeGestureId < 0) {
3342 mPointerGesture.activeGestureId =
3343 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3344#if DEBUG_GESTURES
3345 ALOGD("Gestures: FREEFORM new "
3346 "activeGestureId=%d",
3347 mPointerGesture.activeGestureId);
3348#endif
3349 }
3350 }
3351 }
3352
3353 mPointerController->setButtonState(mCurrentRawState.buttonState);
3354
3355#if DEBUG_GESTURES
3356 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3357 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3358 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3359 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3360 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3361 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3362 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3363 uint32_t id = idBits.clearFirstMarkedBit();
3364 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3365 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3366 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3367 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3368 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3369 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3370 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3371 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3372 }
3373 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3374 uint32_t id = idBits.clearFirstMarkedBit();
3375 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3376 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3377 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3378 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3379 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3380 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3381 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3382 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3383 }
3384#endif
3385 return true;
3386}
3387
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003388void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003389 mPointerSimple.currentCoords.clear();
3390 mPointerSimple.currentProperties.clear();
3391
3392 bool down, hovering;
3393 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3394 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3395 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003396 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3397 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003398
3399 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3400 down = !hovering;
3401
Prabir Pradhand7482e72021-03-09 13:54:55 -08003402 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003403 mPointerSimple.currentCoords.copyFrom(
3404 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3405 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3406 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3407 mPointerSimple.currentProperties.id = 0;
3408 mPointerSimple.currentProperties.toolType =
3409 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3410 } else {
3411 down = false;
3412 hovering = false;
3413 }
3414
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003415 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003416}
3417
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003418void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3419 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003420}
3421
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003422void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003423 mPointerSimple.currentCoords.clear();
3424 mPointerSimple.currentProperties.clear();
3425
3426 bool down, hovering;
3427 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3428 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3429 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3430 float deltaX = 0, deltaY = 0;
3431 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3432 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3433 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3434 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3435 mPointerXMovementScale;
3436 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3437 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3438 mPointerYMovementScale;
3439
3440 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3441 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3442
Prabir Pradhand7482e72021-03-09 13:54:55 -08003443 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003444 } else {
3445 mPointerVelocityControl.reset();
3446 }
3447
3448 down = isPointerDown(mCurrentRawState.buttonState);
3449 hovering = !down;
3450
Prabir Pradhand7482e72021-03-09 13:54:55 -08003451 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003452 mPointerSimple.currentCoords.copyFrom(
3453 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3454 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3455 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3456 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3457 hovering ? 0.0f : 1.0f);
3458 mPointerSimple.currentProperties.id = 0;
3459 mPointerSimple.currentProperties.toolType =
3460 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3461 } else {
3462 mPointerVelocityControl.reset();
3463
3464 down = false;
3465 hovering = false;
3466 }
3467
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003468 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469}
3470
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003471void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3472 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003473
3474 mPointerVelocityControl.reset();
3475}
3476
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003477void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3478 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003479 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003480
3481 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003482 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003483 mPointerController->clearSpots();
3484 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003485 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003486 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003487 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003488 }
Garfield Tan9514d782020-11-10 16:37:23 -08003489 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003490
Prabir Pradhand7482e72021-03-09 13:54:55 -08003491 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003492
3493 if (mPointerSimple.down && !down) {
3494 mPointerSimple.down = false;
3495
3496 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003497 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3498 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003499 mLastRawState.buttonState, MotionClassification::NONE,
3500 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3501 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3502 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3503 /* videoFrames */ {});
3504 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003505 }
3506
3507 if (mPointerSimple.hovering && !hovering) {
3508 mPointerSimple.hovering = false;
3509
3510 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003511 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3512 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3513 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003514 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3515 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3516 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3517 /* videoFrames */ {});
3518 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003519 }
3520
3521 if (down) {
3522 if (!mPointerSimple.down) {
3523 mPointerSimple.down = true;
3524 mPointerSimple.downTime = when;
3525
3526 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003527 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003528 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3529 metaState, mCurrentRawState.buttonState,
3530 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3531 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3532 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3533 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3534 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003535 }
3536
3537 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003538 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3539 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003540 mCurrentRawState.buttonState, MotionClassification::NONE,
3541 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3542 &mPointerSimple.currentCoords, mOrientedXPrecision,
3543 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3544 mPointerSimple.downTime, /* videoFrames */ {});
3545 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546 }
3547
3548 if (hovering) {
3549 if (!mPointerSimple.hovering) {
3550 mPointerSimple.hovering = true;
3551
3552 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003553 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003554 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3555 metaState, mCurrentRawState.buttonState,
3556 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3557 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3558 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3559 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3560 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003561 }
3562
3563 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003564 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3565 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3566 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003567 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3568 &mPointerSimple.currentCoords, mOrientedXPrecision,
3569 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3570 mPointerSimple.downTime, /* videoFrames */ {});
3571 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572 }
3573
3574 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3575 float vscroll = mCurrentRawState.rawVScroll;
3576 float hscroll = mCurrentRawState.rawHScroll;
3577 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3578 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3579
3580 // Send scroll.
3581 PointerCoords pointerCoords;
3582 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3583 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3584 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3585
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003586 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3587 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003588 mCurrentRawState.buttonState, MotionClassification::NONE,
3589 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3590 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3591 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3592 /* videoFrames */ {});
3593 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003594 }
3595
3596 // Save state.
3597 if (down || hovering) {
3598 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3599 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3600 } else {
3601 mPointerSimple.reset();
3602 }
3603}
3604
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003605void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606 mPointerSimple.currentCoords.clear();
3607 mPointerSimple.currentProperties.clear();
3608
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003609 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003610}
3611
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003612void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3613 uint32_t source, int32_t action, int32_t actionButton,
3614 int32_t flags, int32_t metaState, int32_t buttonState,
3615 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003616 const PointerCoords* coords, const uint32_t* idToIndex,
3617 BitSet32 idBits, int32_t changedId, float xPrecision,
3618 float yPrecision, nsecs_t downTime) {
3619 PointerCoords pointerCoords[MAX_POINTERS];
3620 PointerProperties pointerProperties[MAX_POINTERS];
3621 uint32_t pointerCount = 0;
3622 while (!idBits.isEmpty()) {
3623 uint32_t id = idBits.clearFirstMarkedBit();
3624 uint32_t index = idToIndex[id];
3625 pointerProperties[pointerCount].copyFrom(properties[index]);
3626 pointerCoords[pointerCount].copyFrom(coords[index]);
3627
3628 if (changedId >= 0 && id == uint32_t(changedId)) {
3629 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3630 }
3631
3632 pointerCount += 1;
3633 }
3634
3635 ALOG_ASSERT(pointerCount != 0);
3636
3637 if (changedId >= 0 && pointerCount == 1) {
3638 // Replace initial down and final up action.
3639 // We can compare the action without masking off the changed pointer index
3640 // because we know the index is 0.
3641 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3642 action = AMOTION_EVENT_ACTION_DOWN;
3643 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003644 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3645 action = AMOTION_EVENT_ACTION_CANCEL;
3646 } else {
3647 action = AMOTION_EVENT_ACTION_UP;
3648 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003649 } else {
3650 // Can't happen.
3651 ALOG_ASSERT(false);
3652 }
3653 }
3654 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3655 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003656 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003657 auto [x, y] = getMouseCursorPosition();
3658 xCursorPosition = x;
3659 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003660 }
3661 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3662 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003663 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003664 std::for_each(frames.begin(), frames.end(),
3665 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003666 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3667 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003668 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3669 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3670 downTime, std::move(frames));
3671 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003672}
3673
3674bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3675 const PointerCoords* inCoords,
3676 const uint32_t* inIdToIndex,
3677 PointerProperties* outProperties,
3678 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3679 BitSet32 idBits) const {
3680 bool changed = false;
3681 while (!idBits.isEmpty()) {
3682 uint32_t id = idBits.clearFirstMarkedBit();
3683 uint32_t inIndex = inIdToIndex[id];
3684 uint32_t outIndex = outIdToIndex[id];
3685
3686 const PointerProperties& curInProperties = inProperties[inIndex];
3687 const PointerCoords& curInCoords = inCoords[inIndex];
3688 PointerProperties& curOutProperties = outProperties[outIndex];
3689 PointerCoords& curOutCoords = outCoords[outIndex];
3690
3691 if (curInProperties != curOutProperties) {
3692 curOutProperties.copyFrom(curInProperties);
3693 changed = true;
3694 }
3695
3696 if (curInCoords != curOutCoords) {
3697 curOutCoords.copyFrom(curInCoords);
3698 changed = true;
3699 }
3700 }
3701 return changed;
3702}
3703
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003704void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3705 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3706 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003707}
3708
Arthur Hung4197f6b2020-03-16 15:39:59 +08003709// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003710void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003711 // Scale to surface coordinate.
3712 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3713 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3714
arthurhunga36b28e2020-12-29 20:28:15 +08003715 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3716 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3717
Arthur Hung4197f6b2020-03-16 15:39:59 +08003718 // Rotate to surface coordinate.
3719 // 0 - no swap and reverse.
3720 // 90 - swap x/y and reverse y.
3721 // 180 - reverse x, y.
3722 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003723 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003724 case DISPLAY_ORIENTATION_0:
3725 x = xScaled + mXTranslate;
3726 y = yScaled + mYTranslate;
3727 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003728 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003729 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003730 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003731 break;
3732 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003733 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3734 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003735 break;
3736 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003737 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003738 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003739 break;
3740 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003741 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003742 }
3743}
3744
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003745bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003746 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3747 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3748
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003749 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003750 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003751 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003752 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003753}
3754
3755const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3756 for (const VirtualKey& virtualKey : mVirtualKeys) {
3757#if DEBUG_VIRTUAL_KEYS
3758 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3759 "left=%d, top=%d, right=%d, bottom=%d",
3760 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3761 virtualKey.hitRight, virtualKey.hitBottom);
3762#endif
3763
3764 if (virtualKey.isHit(x, y)) {
3765 return &virtualKey;
3766 }
3767 }
3768
3769 return nullptr;
3770}
3771
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003772void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3773 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3774 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003775
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003776 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003777
3778 if (currentPointerCount == 0) {
3779 // No pointers to assign.
3780 return;
3781 }
3782
3783 if (lastPointerCount == 0) {
3784 // All pointers are new.
3785 for (uint32_t i = 0; i < currentPointerCount; i++) {
3786 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003787 current.rawPointerData.pointers[i].id = id;
3788 current.rawPointerData.idToIndex[id] = i;
3789 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003790 }
3791 return;
3792 }
3793
3794 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003795 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003796 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003797 uint32_t id = last.rawPointerData.pointers[0].id;
3798 current.rawPointerData.pointers[0].id = id;
3799 current.rawPointerData.idToIndex[id] = 0;
3800 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003801 return;
3802 }
3803
3804 // General case.
3805 // We build a heap of squared euclidean distances between current and last pointers
3806 // associated with the current and last pointer indices. Then, we find the best
3807 // match (by distance) for each current pointer.
3808 // The pointers must have the same tool type but it is possible for them to
3809 // transition from hovering to touching or vice-versa while retaining the same id.
3810 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3811
3812 uint32_t heapSize = 0;
3813 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3814 currentPointerIndex++) {
3815 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3816 lastPointerIndex++) {
3817 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003818 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003819 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003820 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003821 if (currentPointer.toolType == lastPointer.toolType) {
3822 int64_t deltaX = currentPointer.x - lastPointer.x;
3823 int64_t deltaY = currentPointer.y - lastPointer.y;
3824
3825 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3826
3827 // Insert new element into the heap (sift up).
3828 heap[heapSize].currentPointerIndex = currentPointerIndex;
3829 heap[heapSize].lastPointerIndex = lastPointerIndex;
3830 heap[heapSize].distance = distance;
3831 heapSize += 1;
3832 }
3833 }
3834 }
3835
3836 // Heapify
3837 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3838 startIndex -= 1;
3839 for (uint32_t parentIndex = startIndex;;) {
3840 uint32_t childIndex = parentIndex * 2 + 1;
3841 if (childIndex >= heapSize) {
3842 break;
3843 }
3844
3845 if (childIndex + 1 < heapSize &&
3846 heap[childIndex + 1].distance < heap[childIndex].distance) {
3847 childIndex += 1;
3848 }
3849
3850 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3851 break;
3852 }
3853
3854 swap(heap[parentIndex], heap[childIndex]);
3855 parentIndex = childIndex;
3856 }
3857 }
3858
3859#if DEBUG_POINTER_ASSIGNMENT
3860 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3861 for (size_t i = 0; i < heapSize; i++) {
3862 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3863 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3864 }
3865#endif
3866
3867 // Pull matches out by increasing order of distance.
3868 // To avoid reassigning pointers that have already been matched, the loop keeps track
3869 // of which last and current pointers have been matched using the matchedXXXBits variables.
3870 // It also tracks the used pointer id bits.
3871 BitSet32 matchedLastBits(0);
3872 BitSet32 matchedCurrentBits(0);
3873 BitSet32 usedIdBits(0);
3874 bool first = true;
3875 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3876 while (heapSize > 0) {
3877 if (first) {
3878 // The first time through the loop, we just consume the root element of
3879 // the heap (the one with smallest distance).
3880 first = false;
3881 } else {
3882 // Previous iterations consumed the root element of the heap.
3883 // Pop root element off of the heap (sift down).
3884 heap[0] = heap[heapSize];
3885 for (uint32_t parentIndex = 0;;) {
3886 uint32_t childIndex = parentIndex * 2 + 1;
3887 if (childIndex >= heapSize) {
3888 break;
3889 }
3890
3891 if (childIndex + 1 < heapSize &&
3892 heap[childIndex + 1].distance < heap[childIndex].distance) {
3893 childIndex += 1;
3894 }
3895
3896 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3897 break;
3898 }
3899
3900 swap(heap[parentIndex], heap[childIndex]);
3901 parentIndex = childIndex;
3902 }
3903
3904#if DEBUG_POINTER_ASSIGNMENT
3905 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003906 for (size_t j = 0; j < heapSize; j++) {
3907 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3908 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003909 }
3910#endif
3911 }
3912
3913 heapSize -= 1;
3914
3915 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3916 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3917
3918 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3919 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3920
3921 matchedCurrentBits.markBit(currentPointerIndex);
3922 matchedLastBits.markBit(lastPointerIndex);
3923
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003924 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3925 current.rawPointerData.pointers[currentPointerIndex].id = id;
3926 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3927 current.rawPointerData.markIdBit(id,
3928 current.rawPointerData.isHovering(
3929 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003930 usedIdBits.markBit(id);
3931
3932#if DEBUG_POINTER_ASSIGNMENT
3933 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3934 ", distance=%" PRIu64,
3935 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3936#endif
3937 break;
3938 }
3939 }
3940
3941 // Assign fresh ids to pointers that were not matched in the process.
3942 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3943 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3944 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3945
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003946 current.rawPointerData.pointers[currentPointerIndex].id = id;
3947 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3948 current.rawPointerData.markIdBit(id,
3949 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003950
3951#if DEBUG_POINTER_ASSIGNMENT
3952 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3953#endif
3954 }
3955}
3956
3957int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3958 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3959 return AKEY_STATE_VIRTUAL;
3960 }
3961
3962 for (const VirtualKey& virtualKey : mVirtualKeys) {
3963 if (virtualKey.keyCode == keyCode) {
3964 return AKEY_STATE_UP;
3965 }
3966 }
3967
3968 return AKEY_STATE_UNKNOWN;
3969}
3970
3971int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3972 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3973 return AKEY_STATE_VIRTUAL;
3974 }
3975
3976 for (const VirtualKey& virtualKey : mVirtualKeys) {
3977 if (virtualKey.scanCode == scanCode) {
3978 return AKEY_STATE_UP;
3979 }
3980 }
3981
3982 return AKEY_STATE_UNKNOWN;
3983}
3984
3985bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3986 const int32_t* keyCodes, uint8_t* outFlags) {
3987 for (const VirtualKey& virtualKey : mVirtualKeys) {
3988 for (size_t i = 0; i < numCodes; i++) {
3989 if (virtualKey.keyCode == keyCodes[i]) {
3990 outFlags[i] = 1;
3991 }
3992 }
3993 }
3994
3995 return true;
3996}
3997
3998std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3999 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004000 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004001 return std::make_optional(mPointerController->getDisplayId());
4002 } else {
4003 return std::make_optional(mViewport.displayId);
4004 }
4005 }
4006 return std::nullopt;
4007}
4008
Prabir Pradhand7482e72021-03-09 13:54:55 -08004009void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
4010 if (isPerWindowInputRotationEnabled()) {
4011 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4012 // space that is oriented with the viewport.
4013 rotateDelta(mViewport.orientation, &dx, &dy);
4014 }
4015
4016 mPointerController->move(dx, dy);
4017}
4018
4019std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4020 float x = 0;
4021 float y = 0;
4022 mPointerController->getPosition(&x, &y);
4023
4024 if (!isPerWindowInputRotationEnabled()) return {x, y};
4025 if (!mViewport.isValid()) return {x, y};
4026
4027 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4028 // to InputReader's un-rotated coordinate space.
4029 const int32_t orientation = getInverseRotation(mViewport.orientation);
4030 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4031 return {x, y};
4032}
4033
4034void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4035 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4036 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4037 // coordinate space that is oriented with the viewport.
4038 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4039 }
4040
4041 mPointerController->setPosition(x, y);
4042}
4043
4044void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4045 BitSet32 spotIdBits, int32_t displayId) {
4046 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4047
4048 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4049 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4050 float x = spotCoords[index].getX();
4051 float y = spotCoords[index].getY();
4052 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4053
4054 if (isPerWindowInputRotationEnabled()) {
4055 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4056 // coordinate space.
4057 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4058 }
4059
4060 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4061 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4062 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4063 }
4064
4065 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4066}
4067
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004068} // namespace android