blob: 13712eee539057d86cb39001b20946468942717e [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;
685 if (viewportChanged) {
686 mViewport = *newViewport;
687
Michael Wright227c5542020-07-02 18:30:52 +0100688 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700689 // Convert rotated viewport to natural surface coordinates.
690 int32_t naturalLogicalWidth, naturalLogicalHeight;
691 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
692 int32_t naturalPhysicalLeft, naturalPhysicalTop;
693 int32_t naturalDeviceWidth, naturalDeviceHeight;
694 switch (mViewport.orientation) {
695 case DISPLAY_ORIENTATION_90:
696 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
697 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
698 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
699 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800700 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700701 naturalPhysicalTop = mViewport.physicalLeft;
702 naturalDeviceWidth = mViewport.deviceHeight;
703 naturalDeviceHeight = mViewport.deviceWidth;
704 break;
705 case DISPLAY_ORIENTATION_180:
706 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
707 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
708 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
709 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
710 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
711 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
712 naturalDeviceWidth = mViewport.deviceWidth;
713 naturalDeviceHeight = mViewport.deviceHeight;
714 break;
715 case DISPLAY_ORIENTATION_270:
716 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
717 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
718 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
719 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
720 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800721 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700722 naturalDeviceWidth = mViewport.deviceHeight;
723 naturalDeviceHeight = mViewport.deviceWidth;
724 break;
725 case DISPLAY_ORIENTATION_0:
726 default:
727 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
728 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
729 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
730 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
731 naturalPhysicalLeft = mViewport.physicalLeft;
732 naturalPhysicalTop = mViewport.physicalTop;
733 naturalDeviceWidth = mViewport.deviceWidth;
734 naturalDeviceHeight = mViewport.deviceHeight;
735 break;
736 }
737
738 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
739 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
740 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
741 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
742 }
743
744 mPhysicalWidth = naturalPhysicalWidth;
745 mPhysicalHeight = naturalPhysicalHeight;
746 mPhysicalLeft = naturalPhysicalLeft;
747 mPhysicalTop = naturalPhysicalTop;
748
Arthur Hung4197f6b2020-03-16 15:39:59 +0800749 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
750 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700751 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
752 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800753 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
754 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700755
Prabir Pradhand7482e72021-03-09 13:54:55 -0800756 if (isPerWindowInputRotationEnabled()) {
757 // When per-window input rotation is enabled, InputReader works in the un-rotated
758 // coordinate space, so we don't need to do anything if the device is already
759 // orientation-aware. If the device is not orientation-aware, then we need to apply
760 // the inverse rotation of the display so that when the display rotation is applied
761 // later as a part of the per-window transform, we get the expected screen
762 // coordinates.
763 mSurfaceOrientation = mParameters.orientationAware
764 ? DISPLAY_ORIENTATION_0
765 : getInverseRotation(mViewport.orientation);
766 } else {
767 mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation
768 : DISPLAY_ORIENTATION_0;
769 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700770 } else {
771 mPhysicalWidth = rawWidth;
772 mPhysicalHeight = rawHeight;
773 mPhysicalLeft = 0;
774 mPhysicalTop = 0;
775
Arthur Hung4197f6b2020-03-16 15:39:59 +0800776 mRawSurfaceWidth = rawWidth;
777 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700778 mSurfaceLeft = 0;
779 mSurfaceTop = 0;
780 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
781 }
782 }
783
784 // If moving between pointer modes, need to reset some state.
785 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
786 if (deviceModeChanged) {
787 mOrientedRanges.clear();
788 }
789
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800790 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
791 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100792 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800793 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
794 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800795 if (mPointerController == nullptr) {
796 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700797 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800798 if (mConfig.pointerCapture) {
799 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
800 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700801 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100802 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700803 }
804
805 if (viewportChanged || deviceModeChanged) {
806 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
807 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800808 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700809 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
810
811 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800812 mXScale = float(mRawSurfaceWidth) / rawWidth;
813 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700814 mXTranslate = -mSurfaceLeft;
815 mYTranslate = -mSurfaceTop;
816 mXPrecision = 1.0f / mXScale;
817 mYPrecision = 1.0f / mYScale;
818
819 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
820 mOrientedRanges.x.source = mSource;
821 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
822 mOrientedRanges.y.source = mSource;
823
824 configureVirtualKeys();
825
826 // Scale factor for terms that are not oriented in a particular axis.
827 // If the pixels are square then xScale == yScale otherwise we fake it
828 // by choosing an average.
829 mGeometricScale = avg(mXScale, mYScale);
830
831 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800832 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700833
834 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100835 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700836 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
837 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
838 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
839 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
840 } else {
841 mSizeScale = 0.0f;
842 }
843
844 mOrientedRanges.haveTouchSize = true;
845 mOrientedRanges.haveToolSize = true;
846 mOrientedRanges.haveSize = true;
847
848 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
849 mOrientedRanges.touchMajor.source = mSource;
850 mOrientedRanges.touchMajor.min = 0;
851 mOrientedRanges.touchMajor.max = diagonalSize;
852 mOrientedRanges.touchMajor.flat = 0;
853 mOrientedRanges.touchMajor.fuzz = 0;
854 mOrientedRanges.touchMajor.resolution = 0;
855
856 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
857 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
858
859 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
860 mOrientedRanges.toolMajor.source = mSource;
861 mOrientedRanges.toolMajor.min = 0;
862 mOrientedRanges.toolMajor.max = diagonalSize;
863 mOrientedRanges.toolMajor.flat = 0;
864 mOrientedRanges.toolMajor.fuzz = 0;
865 mOrientedRanges.toolMajor.resolution = 0;
866
867 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
868 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
869
870 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
871 mOrientedRanges.size.source = mSource;
872 mOrientedRanges.size.min = 0;
873 mOrientedRanges.size.max = 1.0;
874 mOrientedRanges.size.flat = 0;
875 mOrientedRanges.size.fuzz = 0;
876 mOrientedRanges.size.resolution = 0;
877 } else {
878 mSizeScale = 0.0f;
879 }
880
881 // Pressure factors.
882 mPressureScale = 0;
883 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100884 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
885 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700886 if (mCalibration.havePressureScale) {
887 mPressureScale = mCalibration.pressureScale;
888 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
889 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
890 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
891 }
892 }
893
894 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
895 mOrientedRanges.pressure.source = mSource;
896 mOrientedRanges.pressure.min = 0;
897 mOrientedRanges.pressure.max = pressureMax;
898 mOrientedRanges.pressure.flat = 0;
899 mOrientedRanges.pressure.fuzz = 0;
900 mOrientedRanges.pressure.resolution = 0;
901
902 // Tilt
903 mTiltXCenter = 0;
904 mTiltXScale = 0;
905 mTiltYCenter = 0;
906 mTiltYScale = 0;
907 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
908 if (mHaveTilt) {
909 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
910 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
911 mTiltXScale = M_PI / 180;
912 mTiltYScale = M_PI / 180;
913
914 mOrientedRanges.haveTilt = true;
915
916 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
917 mOrientedRanges.tilt.source = mSource;
918 mOrientedRanges.tilt.min = 0;
919 mOrientedRanges.tilt.max = M_PI_2;
920 mOrientedRanges.tilt.flat = 0;
921 mOrientedRanges.tilt.fuzz = 0;
922 mOrientedRanges.tilt.resolution = 0;
923 }
924
925 // Orientation
926 mOrientationScale = 0;
927 if (mHaveTilt) {
928 mOrientedRanges.haveOrientation = true;
929
930 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
931 mOrientedRanges.orientation.source = mSource;
932 mOrientedRanges.orientation.min = -M_PI;
933 mOrientedRanges.orientation.max = M_PI;
934 mOrientedRanges.orientation.flat = 0;
935 mOrientedRanges.orientation.fuzz = 0;
936 mOrientedRanges.orientation.resolution = 0;
937 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100938 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700939 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100940 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700941 if (mRawPointerAxes.orientation.valid) {
942 if (mRawPointerAxes.orientation.maxValue > 0) {
943 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
944 } else if (mRawPointerAxes.orientation.minValue < 0) {
945 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
946 } else {
947 mOrientationScale = 0;
948 }
949 }
950 }
951
952 mOrientedRanges.haveOrientation = true;
953
954 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
955 mOrientedRanges.orientation.source = mSource;
956 mOrientedRanges.orientation.min = -M_PI_2;
957 mOrientedRanges.orientation.max = M_PI_2;
958 mOrientedRanges.orientation.flat = 0;
959 mOrientedRanges.orientation.fuzz = 0;
960 mOrientedRanges.orientation.resolution = 0;
961 }
962
963 // Distance
964 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100965 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
966 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700967 if (mCalibration.haveDistanceScale) {
968 mDistanceScale = mCalibration.distanceScale;
969 } else {
970 mDistanceScale = 1.0f;
971 }
972 }
973
974 mOrientedRanges.haveDistance = true;
975
976 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
977 mOrientedRanges.distance.source = mSource;
978 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
979 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
980 mOrientedRanges.distance.flat = 0;
981 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
982 mOrientedRanges.distance.resolution = 0;
983 }
984
985 // Compute oriented precision, scales and ranges.
986 // Note that the maximum value reported is an inclusive maximum value so it is one
987 // unit less than the total width or height of surface.
988 switch (mSurfaceOrientation) {
989 case DISPLAY_ORIENTATION_90:
990 case DISPLAY_ORIENTATION_270:
991 mOrientedXPrecision = mYPrecision;
992 mOrientedYPrecision = mXPrecision;
993
994 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800995 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996 mOrientedRanges.x.flat = 0;
997 mOrientedRanges.x.fuzz = 0;
998 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
999
1000 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001001 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001002 mOrientedRanges.y.flat = 0;
1003 mOrientedRanges.y.fuzz = 0;
1004 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
1005 break;
1006
1007 default:
1008 mOrientedXPrecision = mXPrecision;
1009 mOrientedYPrecision = mYPrecision;
1010
1011 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001012 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001013 mOrientedRanges.x.flat = 0;
1014 mOrientedRanges.x.fuzz = 0;
1015 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1016
1017 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001018 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001019 mOrientedRanges.y.flat = 0;
1020 mOrientedRanges.y.fuzz = 0;
1021 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1022 break;
1023 }
1024
1025 // Location
1026 updateAffineTransformation();
1027
Michael Wright227c5542020-07-02 18:30:52 +01001028 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001029 // Compute pointer gesture detection parameters.
1030 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001031 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032
1033 // Scale movements such that one whole swipe of the touch pad covers a
1034 // given area relative to the diagonal size of the display when no acceleration
1035 // is applied.
1036 // Assume that the touch pad has a square aspect ratio such that movements in
1037 // X and Y of the same number of raw units cover the same physical distance.
1038 mPointerXMovementScale =
1039 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1040 mPointerYMovementScale = mPointerXMovementScale;
1041
1042 // Scale zooms to cover a smaller range of the display than movements do.
1043 // This value determines the area around the pointer that is affected by freeform
1044 // pointer gestures.
1045 mPointerXZoomScale =
1046 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1047 mPointerYZoomScale = mPointerXZoomScale;
1048
1049 // Max width between pointers to detect a swipe gesture is more than some fraction
1050 // of the diagonal axis of the touch pad. Touches that are wider than this are
1051 // translated into freeform gestures.
1052 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1053
1054 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001055 const nsecs_t readTime = when; // synthetic event
1056 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057 }
1058
1059 // Inform the dispatcher about the changes.
1060 *outResetNeeded = true;
1061 bumpGeneration();
1062 }
1063}
1064
1065void TouchInputMapper::dumpSurface(std::string& dump) {
1066 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001067 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1068 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001069 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1070 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001071 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1072 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001073 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1074 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1075 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1076 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1077 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1078}
1079
1080void TouchInputMapper::configureVirtualKeys() {
1081 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001082 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001083
1084 mVirtualKeys.clear();
1085
1086 if (virtualKeyDefinitions.size() == 0) {
1087 return;
1088 }
1089
1090 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1091 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1092 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1093 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1094
1095 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1096 VirtualKey virtualKey;
1097
1098 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1099 int32_t keyCode;
1100 int32_t dummyKeyMetaState;
1101 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001102 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1103 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1105 continue; // drop the key
1106 }
1107
1108 virtualKey.keyCode = keyCode;
1109 virtualKey.flags = flags;
1110
1111 // convert the key definition's display coordinates into touch coordinates for a hit box
1112 int32_t halfWidth = virtualKeyDefinition.width / 2;
1113 int32_t halfHeight = virtualKeyDefinition.height / 2;
1114
1115 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001116 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 touchScreenLeft;
1118 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001119 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001120 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001121 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1122 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001124 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1125 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 touchScreenTop;
1127 mVirtualKeys.push_back(virtualKey);
1128 }
1129}
1130
1131void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1132 if (!mVirtualKeys.empty()) {
1133 dump += INDENT3 "Virtual Keys:\n";
1134
1135 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1136 const VirtualKey& virtualKey = mVirtualKeys[i];
1137 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1138 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1139 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1140 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1141 }
1142 }
1143}
1144
1145void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001146 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 Calibration& out = mCalibration;
1148
1149 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001150 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 String8 sizeCalibrationString;
1152 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1153 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001154 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001156 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001157 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001158 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001160 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001161 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001163 } else if (sizeCalibrationString != "default") {
1164 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1165 }
1166 }
1167
1168 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1169 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1170 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1171
1172 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 String8 pressureCalibrationString;
1175 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1176 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 } else if (pressureCalibrationString != "default") {
1183 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1184 pressureCalibrationString.string());
1185 }
1186 }
1187
1188 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1189
1190 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 String8 orientationCalibrationString;
1193 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1194 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (orientationCalibrationString != "default") {
1201 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1202 orientationCalibrationString.string());
1203 }
1204 }
1205
1206 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 String8 distanceCalibrationString;
1209 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1210 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 } else if (distanceCalibrationString != "default") {
1215 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1216 distanceCalibrationString.string());
1217 }
1218 }
1219
1220 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1221
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 String8 coverageCalibrationString;
1224 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1225 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001226 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001228 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 } else if (coverageCalibrationString != "default") {
1230 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1231 coverageCalibrationString.string());
1232 }
1233 }
1234}
1235
1236void TouchInputMapper::resolveCalibration() {
1237 // Size
1238 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001239 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1240 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001243 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 }
1245
1246 // Pressure
1247 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001248 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1249 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001252 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 }
1254
1255 // Orientation
1256 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001257 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1258 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001261 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263
1264 // Distance
1265 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001266 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1267 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 }
1269 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001270 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272
1273 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001274 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1275 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 }
1277}
1278
1279void TouchInputMapper::dumpCalibration(std::string& dump) {
1280 dump += INDENT3 "Calibration:\n";
1281
1282 // Size
1283 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001284 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 dump += INDENT4 "touch.size.calibration: none\n";
1286 break;
Michael Wright227c5542020-07-02 18:30:52 +01001287 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 dump += INDENT4 "touch.size.calibration: geometric\n";
1289 break;
Michael Wright227c5542020-07-02 18:30:52 +01001290 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 dump += INDENT4 "touch.size.calibration: diameter\n";
1292 break;
Michael Wright227c5542020-07-02 18:30:52 +01001293 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 dump += INDENT4 "touch.size.calibration: box\n";
1295 break;
Michael Wright227c5542020-07-02 18:30:52 +01001296 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 dump += INDENT4 "touch.size.calibration: area\n";
1298 break;
1299 default:
1300 ALOG_ASSERT(false);
1301 }
1302
1303 if (mCalibration.haveSizeScale) {
1304 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1305 }
1306
1307 if (mCalibration.haveSizeBias) {
1308 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1309 }
1310
1311 if (mCalibration.haveSizeIsSummed) {
1312 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1313 toString(mCalibration.sizeIsSummed));
1314 }
1315
1316 // Pressure
1317 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.pressure.calibration: none\n";
1320 break;
Michael Wright227c5542020-07-02 18:30:52 +01001321 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += INDENT4 "touch.pressure.calibration: physical\n";
1323 break;
Michael Wright227c5542020-07-02 18:30:52 +01001324 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1326 break;
1327 default:
1328 ALOG_ASSERT(false);
1329 }
1330
1331 if (mCalibration.havePressureScale) {
1332 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1333 }
1334
1335 // Orientation
1336 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001337 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 dump += INDENT4 "touch.orientation.calibration: none\n";
1339 break;
Michael Wright227c5542020-07-02 18:30:52 +01001340 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1342 break;
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.orientation.calibration: vector\n";
1345 break;
1346 default:
1347 ALOG_ASSERT(false);
1348 }
1349
1350 // Distance
1351 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001352 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 dump += INDENT4 "touch.distance.calibration: none\n";
1354 break;
Michael Wright227c5542020-07-02 18:30:52 +01001355 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356 dump += INDENT4 "touch.distance.calibration: scaled\n";
1357 break;
1358 default:
1359 ALOG_ASSERT(false);
1360 }
1361
1362 if (mCalibration.haveDistanceScale) {
1363 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1364 }
1365
1366 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001367 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001368 dump += INDENT4 "touch.coverage.calibration: none\n";
1369 break;
Michael Wright227c5542020-07-02 18:30:52 +01001370 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001371 dump += INDENT4 "touch.coverage.calibration: box\n";
1372 break;
1373 default:
1374 ALOG_ASSERT(false);
1375 }
1376}
1377
1378void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1379 dump += INDENT3 "Affine Transformation:\n";
1380
1381 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1382 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1383 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1384 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1385 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1386 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1387}
1388
1389void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001390 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391 mSurfaceOrientation);
1392}
1393
1394void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001395 mCursorButtonAccumulator.reset(getDeviceContext());
1396 mCursorScrollAccumulator.reset(getDeviceContext());
1397 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001398
1399 mPointerVelocityControl.reset();
1400 mWheelXVelocityControl.reset();
1401 mWheelYVelocityControl.reset();
1402
1403 mRawStatesPending.clear();
1404 mCurrentRawState.clear();
1405 mCurrentCookedState.clear();
1406 mLastRawState.clear();
1407 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001408 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001409 mSentHoverEnter = false;
1410 mHavePointerIds = false;
1411 mCurrentMotionAborted = false;
1412 mDownTime = 0;
1413
1414 mCurrentVirtualKey.down = false;
1415
1416 mPointerGesture.reset();
1417 mPointerSimple.reset();
1418 resetExternalStylus();
1419
1420 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001421 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422 mPointerController->clearSpots();
1423 }
1424
1425 InputMapper::reset(when);
1426}
1427
1428void TouchInputMapper::resetExternalStylus() {
1429 mExternalStylusState.clear();
1430 mExternalStylusId = -1;
1431 mExternalStylusFusionTimeout = LLONG_MAX;
1432 mExternalStylusDataPending = false;
1433}
1434
1435void TouchInputMapper::clearStylusDataPendingFlags() {
1436 mExternalStylusDataPending = false;
1437 mExternalStylusFusionTimeout = LLONG_MAX;
1438}
1439
1440void TouchInputMapper::process(const RawEvent* rawEvent) {
1441 mCursorButtonAccumulator.process(rawEvent);
1442 mCursorScrollAccumulator.process(rawEvent);
1443 mTouchButtonAccumulator.process(rawEvent);
1444
1445 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001446 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447 }
1448}
1449
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001450void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451 // Push a new state.
1452 mRawStatesPending.emplace_back();
1453
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001454 RawState& next = mRawStatesPending.back();
1455 next.clear();
1456 next.when = when;
1457 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001458
1459 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001460 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001461 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1462
1463 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001464 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1465 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001466 mCursorScrollAccumulator.finishSync();
1467
1468 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001469 syncTouch(when, &next);
1470
1471 // The last RawState is the actually second to last, since we just added a new state
1472 const RawState& last =
1473 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001474
1475 // Assign pointer ids.
1476 if (!mHavePointerIds) {
1477 assignPointerIds(last, next);
1478 }
1479
1480#if DEBUG_RAW_EVENTS
1481 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001482 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001483 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1484 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1485 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1486 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001487#endif
1488
1489 processRawTouches(false /*timeout*/);
1490}
1491
1492void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001493 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001494 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001495 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001496 mCurrentCookedState.clear();
1497 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498 return;
1499 }
1500
1501 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1502 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1503 // touching the current state will only observe the events that have been dispatched to the
1504 // rest of the pipeline.
1505 const size_t N = mRawStatesPending.size();
1506 size_t count;
1507 for (count = 0; count < N; count++) {
1508 const RawState& next = mRawStatesPending[count];
1509
1510 // A failure to assign the stylus id means that we're waiting on stylus data
1511 // and so should defer the rest of the pipeline.
1512 if (assignExternalStylusId(next, timeout)) {
1513 break;
1514 }
1515
1516 // All ready to go.
1517 clearStylusDataPendingFlags();
1518 mCurrentRawState.copyFrom(next);
1519 if (mCurrentRawState.when < mLastRawState.when) {
1520 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001521 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001523 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 }
1525 if (count != 0) {
1526 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1527 }
1528
1529 if (mExternalStylusDataPending) {
1530 if (timeout) {
1531 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1532 clearStylusDataPendingFlags();
1533 mCurrentRawState.copyFrom(mLastRawState);
1534#if DEBUG_STYLUS_FUSION
1535 ALOGD("Timeout expired, synthesizing event with new stylus data");
1536#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001537 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1538 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001539 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1540 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1541 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1542 }
1543 }
1544}
1545
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001546void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001547 // Always start with a clean state.
1548 mCurrentCookedState.clear();
1549
1550 // Apply stylus buttons to current raw state.
1551 applyExternalStylusButtonState(when);
1552
1553 // Handle policy on initial down or hover events.
1554 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1555 mCurrentRawState.rawPointerData.pointerCount != 0;
1556
1557 uint32_t policyFlags = 0;
1558 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1559 if (initialDown || buttonsPressed) {
1560 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001561 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001562 getContext()->fadePointer();
1563 }
1564
1565 if (mParameters.wake) {
1566 policyFlags |= POLICY_FLAG_WAKE;
1567 }
1568 }
1569
1570 // Consume raw off-screen touches before cooking pointer data.
1571 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001572 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001573 mCurrentRawState.rawPointerData.clear();
1574 }
1575
1576 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1577 // with cooked pointer data that has the same ids and indices as the raw data.
1578 // The following code can use either the raw or cooked data, as needed.
1579 cookPointerData();
1580
1581 // Apply stylus pressure to current cooked state.
1582 applyExternalStylusTouchState(when);
1583
1584 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001585 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1586 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001587 mCurrentCookedState.buttonState);
1588
1589 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001590 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1592 uint32_t id = idBits.clearFirstMarkedBit();
1593 const RawPointerData::Pointer& pointer =
1594 mCurrentRawState.rawPointerData.pointerForId(id);
1595 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1596 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1597 mCurrentCookedState.stylusIdBits.markBit(id);
1598 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1599 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1600 mCurrentCookedState.fingerIdBits.markBit(id);
1601 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1602 mCurrentCookedState.mouseIdBits.markBit(id);
1603 }
1604 }
1605 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1606 uint32_t id = idBits.clearFirstMarkedBit();
1607 const RawPointerData::Pointer& pointer =
1608 mCurrentRawState.rawPointerData.pointerForId(id);
1609 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1610 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1611 mCurrentCookedState.stylusIdBits.markBit(id);
1612 }
1613 }
1614
1615 // Stylus takes precedence over all tools, then mouse, then finger.
1616 PointerUsage pointerUsage = mPointerUsage;
1617 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1618 mCurrentCookedState.mouseIdBits.clear();
1619 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001620 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001621 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1622 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001623 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1625 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001626 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627 }
1628
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001629 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001631 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632
1633 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001634 dispatchButtonRelease(when, readTime, policyFlags);
1635 dispatchHoverExit(when, readTime, policyFlags);
1636 dispatchTouches(when, readTime, policyFlags);
1637 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1638 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001639 }
1640
1641 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1642 mCurrentMotionAborted = false;
1643 }
1644 }
1645
1646 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001647 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001648 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1649 mCurrentCookedState.buttonState);
1650
1651 // Clear some transient state.
1652 mCurrentRawState.rawVScroll = 0;
1653 mCurrentRawState.rawHScroll = 0;
1654
1655 // Copy current touch to last touch in preparation for the next cycle.
1656 mLastRawState.copyFrom(mCurrentRawState);
1657 mLastCookedState.copyFrom(mCurrentCookedState);
1658}
1659
Garfield Tanc734e4f2021-01-15 20:01:39 -08001660void TouchInputMapper::updateTouchSpots() {
1661 if (!mConfig.showTouches || mPointerController == nullptr) {
1662 return;
1663 }
1664
1665 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1666 // clear touch spots.
1667 if (mDeviceMode != DeviceMode::DIRECT &&
1668 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1669 return;
1670 }
1671
1672 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1673 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1674
1675 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001676 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1677 mCurrentCookedState.cookedPointerData.idToIndex,
1678 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001679}
1680
1681bool TouchInputMapper::isTouchScreen() {
1682 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1683 mParameters.hasAssociatedDisplay;
1684}
1685
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001686void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001687 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001688 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1689 }
1690}
1691
1692void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1693 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1694 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1695
1696 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1697 float pressure = mExternalStylusState.pressure;
1698 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1699 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1700 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1701 }
1702 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1703 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1704
1705 PointerProperties& properties =
1706 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1707 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1708 properties.toolType = mExternalStylusState.toolType;
1709 }
1710 }
1711}
1712
1713bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001714 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001715 return false;
1716 }
1717
1718 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1719 state.rawPointerData.pointerCount != 0;
1720 if (initialDown) {
1721 if (mExternalStylusState.pressure != 0.0f) {
1722#if DEBUG_STYLUS_FUSION
1723 ALOGD("Have both stylus and touch data, beginning fusion");
1724#endif
1725 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1726 } else if (timeout) {
1727#if DEBUG_STYLUS_FUSION
1728 ALOGD("Timeout expired, assuming touch is not a stylus.");
1729#endif
1730 resetExternalStylus();
1731 } else {
1732 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1733 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1734 }
1735#if DEBUG_STYLUS_FUSION
1736 ALOGD("No stylus data but stylus is connected, requesting timeout "
1737 "(%" PRId64 "ms)",
1738 mExternalStylusFusionTimeout);
1739#endif
1740 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1741 return true;
1742 }
1743 }
1744
1745 // Check if the stylus pointer has gone up.
1746 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1747#if DEBUG_STYLUS_FUSION
1748 ALOGD("Stylus pointer is going up");
1749#endif
1750 mExternalStylusId = -1;
1751 }
1752
1753 return false;
1754}
1755
1756void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001757 if (mDeviceMode == DeviceMode::POINTER) {
1758 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001759 // Since this is a synthetic event, we can consider its latency to be zero
1760 const nsecs_t readTime = when;
1761 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001762 }
Michael Wright227c5542020-07-02 18:30:52 +01001763 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001764 if (mExternalStylusFusionTimeout < when) {
1765 processRawTouches(true /*timeout*/);
1766 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1767 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1768 }
1769 }
1770}
1771
1772void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1773 mExternalStylusState.copyFrom(state);
1774 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1775 // We're either in the middle of a fused stream of data or we're waiting on data before
1776 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1777 // data.
1778 mExternalStylusDataPending = true;
1779 processRawTouches(false /*timeout*/);
1780 }
1781}
1782
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001783bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001784 // Check for release of a virtual key.
1785 if (mCurrentVirtualKey.down) {
1786 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1787 // Pointer went up while virtual key was down.
1788 mCurrentVirtualKey.down = false;
1789 if (!mCurrentVirtualKey.ignored) {
1790#if DEBUG_VIRTUAL_KEYS
1791 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1792 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1793#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001794 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001795 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1796 }
1797 return true;
1798 }
1799
1800 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1801 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1802 const RawPointerData::Pointer& pointer =
1803 mCurrentRawState.rawPointerData.pointerForId(id);
1804 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1805 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1806 // Pointer is still within the space of the virtual key.
1807 return true;
1808 }
1809 }
1810
1811 // Pointer left virtual key area or another pointer also went down.
1812 // Send key cancellation but do not consume the touch yet.
1813 // This is useful when the user swipes through from the virtual key area
1814 // into the main display surface.
1815 mCurrentVirtualKey.down = false;
1816 if (!mCurrentVirtualKey.ignored) {
1817#if DEBUG_VIRTUAL_KEYS
1818 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1819 mCurrentVirtualKey.scanCode);
1820#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001821 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001822 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1823 AKEY_EVENT_FLAG_CANCELED);
1824 }
1825 }
1826
1827 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1828 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1829 // Pointer just went down. Check for virtual key press or off-screen touches.
1830 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1831 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001832 // Exclude unscaled device for inside surface checking.
1833 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001834 // If exactly one pointer went down, check for virtual key hit.
1835 // Otherwise we will drop the entire stroke.
1836 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1837 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1838 if (virtualKey) {
1839 mCurrentVirtualKey.down = true;
1840 mCurrentVirtualKey.downTime = when;
1841 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1842 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1843 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001844 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1845 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846
1847 if (!mCurrentVirtualKey.ignored) {
1848#if DEBUG_VIRTUAL_KEYS
1849 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1850 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1851#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001852 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001853 AKEY_EVENT_FLAG_FROM_SYSTEM |
1854 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1855 }
1856 }
1857 }
1858 return true;
1859 }
1860 }
1861
1862 // Disable all virtual key touches that happen within a short time interval of the
1863 // most recent touch within the screen area. The idea is to filter out stray
1864 // virtual key presses when interacting with the touch screen.
1865 //
1866 // Problems we're trying to solve:
1867 //
1868 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1869 // virtual key area that is implemented by a separate touch panel and accidentally
1870 // triggers a virtual key.
1871 //
1872 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1873 // area and accidentally triggers a virtual key. This often happens when virtual keys
1874 // are layed out below the screen near to where the on screen keyboard's space bar
1875 // is displayed.
1876 if (mConfig.virtualKeyQuietTime > 0 &&
1877 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001878 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001879 }
1880 return false;
1881}
1882
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001883void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001884 int32_t keyEventAction, int32_t keyEventFlags) {
1885 int32_t keyCode = mCurrentVirtualKey.keyCode;
1886 int32_t scanCode = mCurrentVirtualKey.scanCode;
1887 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001888 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001889 policyFlags |= POLICY_FLAG_VIRTUAL;
1890
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001891 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1892 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1893 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001894 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001895}
1896
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001897void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001898 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1899 if (!currentIdBits.isEmpty()) {
1900 int32_t metaState = getContext()->getGlobalMetaState();
1901 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001902 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1903 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001904 mCurrentCookedState.cookedPointerData.pointerProperties,
1905 mCurrentCookedState.cookedPointerData.pointerCoords,
1906 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1907 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1908 mCurrentMotionAborted = true;
1909 }
1910}
1911
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001912void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001913 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1914 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1915 int32_t metaState = getContext()->getGlobalMetaState();
1916 int32_t buttonState = mCurrentCookedState.buttonState;
1917
1918 if (currentIdBits == lastIdBits) {
1919 if (!currentIdBits.isEmpty()) {
1920 // No pointer id changes so this is a move event.
1921 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001922 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1923 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924 mCurrentCookedState.cookedPointerData.pointerProperties,
1925 mCurrentCookedState.cookedPointerData.pointerCoords,
1926 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1927 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1928 }
1929 } else {
1930 // There may be pointers going up and pointers going down and pointers moving
1931 // all at the same time.
1932 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1933 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1934 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1935 BitSet32 dispatchedIdBits(lastIdBits.value);
1936
1937 // Update last coordinates of pointers that have moved so that we observe the new
1938 // pointer positions at the same time as other pointers that have just gone up.
1939 bool moveNeeded =
1940 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1941 mCurrentCookedState.cookedPointerData.pointerCoords,
1942 mCurrentCookedState.cookedPointerData.idToIndex,
1943 mLastCookedState.cookedPointerData.pointerProperties,
1944 mLastCookedState.cookedPointerData.pointerCoords,
1945 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1946 if (buttonState != mLastCookedState.buttonState) {
1947 moveNeeded = true;
1948 }
1949
1950 // Dispatch pointer up events.
1951 while (!upIdBits.isEmpty()) {
1952 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001953 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001954 if (isCanceled) {
1955 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1956 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001957 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001958 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001959 mLastCookedState.cookedPointerData.pointerProperties,
1960 mLastCookedState.cookedPointerData.pointerCoords,
1961 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1962 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1963 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001964 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001965 }
1966
1967 // Dispatch move events if any of the remaining pointers moved from their old locations.
1968 // Although applications receive new locations as part of individual pointer up
1969 // events, they do not generally handle them except when presented in a move event.
1970 if (moveNeeded && !moveIdBits.isEmpty()) {
1971 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001972 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1973 metaState, buttonState, 0,
1974 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001975 mCurrentCookedState.cookedPointerData.pointerCoords,
1976 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1977 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1978 }
1979
1980 // Dispatch pointer down events using the new pointer locations.
1981 while (!downIdBits.isEmpty()) {
1982 uint32_t downId = downIdBits.clearFirstMarkedBit();
1983 dispatchedIdBits.markBit(downId);
1984
1985 if (dispatchedIdBits.count() == 1) {
1986 // First pointer is going down. Set down time.
1987 mDownTime = when;
1988 }
1989
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001990 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
1991 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001992 mCurrentCookedState.cookedPointerData.pointerProperties,
1993 mCurrentCookedState.cookedPointerData.pointerCoords,
1994 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1995 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1996 }
1997 }
1998}
1999
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002000void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002001 if (mSentHoverEnter &&
2002 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2003 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2004 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002005 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2006 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002007 mLastCookedState.cookedPointerData.pointerProperties,
2008 mLastCookedState.cookedPointerData.pointerCoords,
2009 mLastCookedState.cookedPointerData.idToIndex,
2010 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2011 mOrientedYPrecision, mDownTime);
2012 mSentHoverEnter = false;
2013 }
2014}
2015
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002016void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2017 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002018 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2019 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2020 int32_t metaState = getContext()->getGlobalMetaState();
2021 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002022 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2023 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002024 mCurrentCookedState.cookedPointerData.pointerProperties,
2025 mCurrentCookedState.cookedPointerData.pointerCoords,
2026 mCurrentCookedState.cookedPointerData.idToIndex,
2027 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2028 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2029 mSentHoverEnter = true;
2030 }
2031
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002032 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2033 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002034 mCurrentCookedState.cookedPointerData.pointerProperties,
2035 mCurrentCookedState.cookedPointerData.pointerCoords,
2036 mCurrentCookedState.cookedPointerData.idToIndex,
2037 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2038 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2039 }
2040}
2041
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002042void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002043 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2044 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2045 const int32_t metaState = getContext()->getGlobalMetaState();
2046 int32_t buttonState = mLastCookedState.buttonState;
2047 while (!releasedButtons.isEmpty()) {
2048 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2049 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002050 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002051 actionButton, 0, metaState, buttonState, 0,
2052 mCurrentCookedState.cookedPointerData.pointerProperties,
2053 mCurrentCookedState.cookedPointerData.pointerCoords,
2054 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2055 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2056 }
2057}
2058
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002059void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002060 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2061 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2062 const int32_t metaState = getContext()->getGlobalMetaState();
2063 int32_t buttonState = mLastCookedState.buttonState;
2064 while (!pressedButtons.isEmpty()) {
2065 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2066 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002067 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2068 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002069 mCurrentCookedState.cookedPointerData.pointerProperties,
2070 mCurrentCookedState.cookedPointerData.pointerCoords,
2071 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2072 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2073 }
2074}
2075
2076const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2077 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2078 return cookedPointerData.touchingIdBits;
2079 }
2080 return cookedPointerData.hoveringIdBits;
2081}
2082
2083void TouchInputMapper::cookPointerData() {
2084 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2085
2086 mCurrentCookedState.cookedPointerData.clear();
2087 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2088 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2089 mCurrentRawState.rawPointerData.hoveringIdBits;
2090 mCurrentCookedState.cookedPointerData.touchingIdBits =
2091 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002092 mCurrentCookedState.cookedPointerData.canceledIdBits =
2093 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002094
2095 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2096 mCurrentCookedState.buttonState = 0;
2097 } else {
2098 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2099 }
2100
2101 // Walk through the the active pointers and map device coordinates onto
2102 // surface coordinates and adjust for display orientation.
2103 for (uint32_t i = 0; i < currentPointerCount; i++) {
2104 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2105
2106 // Size
2107 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2108 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002109 case Calibration::SizeCalibration::GEOMETRIC:
2110 case Calibration::SizeCalibration::DIAMETER:
2111 case Calibration::SizeCalibration::BOX:
2112 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2114 touchMajor = in.touchMajor;
2115 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2116 toolMajor = in.toolMajor;
2117 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2118 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2119 : in.touchMajor;
2120 } else if (mRawPointerAxes.touchMajor.valid) {
2121 toolMajor = touchMajor = in.touchMajor;
2122 toolMinor = touchMinor =
2123 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2124 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2125 : in.touchMajor;
2126 } else if (mRawPointerAxes.toolMajor.valid) {
2127 touchMajor = toolMajor = in.toolMajor;
2128 touchMinor = toolMinor =
2129 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2130 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2131 : in.toolMajor;
2132 } else {
2133 ALOG_ASSERT(false,
2134 "No touch or tool axes. "
2135 "Size calibration should have been resolved to NONE.");
2136 touchMajor = 0;
2137 touchMinor = 0;
2138 toolMajor = 0;
2139 toolMinor = 0;
2140 size = 0;
2141 }
2142
2143 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2144 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2145 if (touchingCount > 1) {
2146 touchMajor /= touchingCount;
2147 touchMinor /= touchingCount;
2148 toolMajor /= touchingCount;
2149 toolMinor /= touchingCount;
2150 size /= touchingCount;
2151 }
2152 }
2153
Michael Wright227c5542020-07-02 18:30:52 +01002154 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002155 touchMajor *= mGeometricScale;
2156 touchMinor *= mGeometricScale;
2157 toolMajor *= mGeometricScale;
2158 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002159 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002160 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2161 touchMinor = touchMajor;
2162 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2163 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002164 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165 touchMinor = touchMajor;
2166 toolMinor = toolMajor;
2167 }
2168
2169 mCalibration.applySizeScaleAndBias(&touchMajor);
2170 mCalibration.applySizeScaleAndBias(&touchMinor);
2171 mCalibration.applySizeScaleAndBias(&toolMajor);
2172 mCalibration.applySizeScaleAndBias(&toolMinor);
2173 size *= mSizeScale;
2174 break;
2175 default:
2176 touchMajor = 0;
2177 touchMinor = 0;
2178 toolMajor = 0;
2179 toolMinor = 0;
2180 size = 0;
2181 break;
2182 }
2183
2184 // Pressure
2185 float pressure;
2186 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002187 case Calibration::PressureCalibration::PHYSICAL:
2188 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002189 pressure = in.pressure * mPressureScale;
2190 break;
2191 default:
2192 pressure = in.isHovering ? 0 : 1;
2193 break;
2194 }
2195
2196 // Tilt and Orientation
2197 float tilt;
2198 float orientation;
2199 if (mHaveTilt) {
2200 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2201 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2202 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2203 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2204 } else {
2205 tilt = 0;
2206
2207 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002208 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002209 orientation = in.orientation * mOrientationScale;
2210 break;
Michael Wright227c5542020-07-02 18:30:52 +01002211 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002212 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2213 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2214 if (c1 != 0 || c2 != 0) {
2215 orientation = atan2f(c1, c2) * 0.5f;
2216 float confidence = hypotf(c1, c2);
2217 float scale = 1.0f + confidence / 16.0f;
2218 touchMajor *= scale;
2219 touchMinor /= scale;
2220 toolMajor *= scale;
2221 toolMinor /= scale;
2222 } else {
2223 orientation = 0;
2224 }
2225 break;
2226 }
2227 default:
2228 orientation = 0;
2229 }
2230 }
2231
2232 // Distance
2233 float distance;
2234 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002235 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002236 distance = in.distance * mDistanceScale;
2237 break;
2238 default:
2239 distance = 0;
2240 }
2241
2242 // Coverage
2243 int32_t rawLeft, rawTop, rawRight, rawBottom;
2244 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002245 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002246 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2247 rawRight = in.toolMinor & 0x0000ffff;
2248 rawBottom = in.toolMajor & 0x0000ffff;
2249 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2250 break;
2251 default:
2252 rawLeft = rawTop = rawRight = rawBottom = 0;
2253 break;
2254 }
2255
2256 // Adjust X,Y coords for device calibration
2257 // TODO: Adjust coverage coords?
2258 float xTransformed = in.x, yTransformed = in.y;
2259 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002260 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002261
2262 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002263 float left, top, right, bottom;
2264
2265 switch (mSurfaceOrientation) {
2266 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002267 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2268 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2269 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2270 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2271 orientation -= M_PI_2;
2272 if (mOrientedRanges.haveOrientation &&
2273 orientation < mOrientedRanges.orientation.min) {
2274 orientation +=
2275 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2276 }
2277 break;
2278 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002279 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2280 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2281 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2282 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2283 orientation -= M_PI;
2284 if (mOrientedRanges.haveOrientation &&
2285 orientation < mOrientedRanges.orientation.min) {
2286 orientation +=
2287 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2288 }
2289 break;
2290 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002291 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2292 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2293 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2294 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2295 orientation += M_PI_2;
2296 if (mOrientedRanges.haveOrientation &&
2297 orientation > mOrientedRanges.orientation.max) {
2298 orientation -=
2299 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2300 }
2301 break;
2302 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2304 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2305 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2306 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2307 break;
2308 }
2309
2310 // Write output coords.
2311 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2312 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002313 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2314 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2316 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2317 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2318 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2319 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2320 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2321 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002322 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2324 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2325 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2326 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2327 } else {
2328 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2329 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2330 }
2331
Chris Ye364fdb52020-08-05 15:07:56 -07002332 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002333 uint32_t id = in.id;
2334 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2335 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2336 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2337 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2338 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2339 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2340 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2341 }
2342
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 // Write output properties.
2344 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345 properties.clear();
2346 properties.id = id;
2347 properties.toolType = in.toolType;
2348
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002349 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002350 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002351 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 }
2353}
2354
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002355void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 PointerUsage pointerUsage) {
2357 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002358 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 mPointerUsage = pointerUsage;
2360 }
2361
2362 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002363 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002364 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 break;
Michael Wright227c5542020-07-02 18:30:52 +01002366 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002367 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 break;
Michael Wright227c5542020-07-02 18:30:52 +01002369 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002370 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 break;
Michael Wright227c5542020-07-02 18:30:52 +01002372 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 break;
2374 }
2375}
2376
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002377void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002379 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002380 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 break;
Michael Wright227c5542020-07-02 18:30:52 +01002382 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002383 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 break;
Michael Wright227c5542020-07-02 18:30:52 +01002385 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002386 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 break;
Michael Wright227c5542020-07-02 18:30:52 +01002388 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 break;
2390 }
2391
Michael Wright227c5542020-07-02 18:30:52 +01002392 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393}
2394
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002395void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2396 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 // Update current gesture coordinates.
2398 bool cancelPreviousGesture, finishPreviousGesture;
2399 bool sendEvents =
2400 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2401 if (!sendEvents) {
2402 return;
2403 }
2404 if (finishPreviousGesture) {
2405 cancelPreviousGesture = false;
2406 }
2407
2408 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002409 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002410 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 if (finishPreviousGesture || cancelPreviousGesture) {
2412 mPointerController->clearSpots();
2413 }
2414
Michael Wright227c5542020-07-02 18:30:52 +01002415 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002416 setTouchSpots(mPointerGesture.currentGestureCoords,
2417 mPointerGesture.currentGestureIdToIndex,
2418 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 }
2420 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002421 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002422 }
2423
2424 // Show or hide the pointer if needed.
2425 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002426 case PointerGesture::Mode::NEUTRAL:
2427 case PointerGesture::Mode::QUIET:
2428 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2429 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002430 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002431 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 }
2433 break;
Michael Wright227c5542020-07-02 18:30:52 +01002434 case PointerGesture::Mode::TAP:
2435 case PointerGesture::Mode::TAP_DRAG:
2436 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2437 case PointerGesture::Mode::HOVER:
2438 case PointerGesture::Mode::PRESS:
2439 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 // Unfade the pointer when the current gesture manipulates the
2441 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002442 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 break;
Michael Wright227c5542020-07-02 18:30:52 +01002444 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 // Fade the pointer when the current gesture manipulates a different
2446 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002447 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002448 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002449 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002450 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451 }
2452 break;
2453 }
2454
2455 // Send events!
2456 int32_t metaState = getContext()->getGlobalMetaState();
2457 int32_t buttonState = mCurrentCookedState.buttonState;
2458
2459 // Update last coordinates of pointers that have moved so that we observe the new
2460 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002461 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2462 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2463 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2464 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2465 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2466 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 bool moveNeeded = false;
2468 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2469 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2470 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2471 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2472 mPointerGesture.lastGestureIdBits.value);
2473 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2474 mPointerGesture.currentGestureCoords,
2475 mPointerGesture.currentGestureIdToIndex,
2476 mPointerGesture.lastGestureProperties,
2477 mPointerGesture.lastGestureCoords,
2478 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2479 if (buttonState != mLastCookedState.buttonState) {
2480 moveNeeded = true;
2481 }
2482 }
2483
2484 // Send motion events for all pointers that went up or were canceled.
2485 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2486 if (!dispatchedGestureIdBits.isEmpty()) {
2487 if (cancelPreviousGesture) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002488 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2489 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2491 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2492 mPointerGesture.downTime);
2493
2494 dispatchedGestureIdBits.clear();
2495 } else {
2496 BitSet32 upGestureIdBits;
2497 if (finishPreviousGesture) {
2498 upGestureIdBits = dispatchedGestureIdBits;
2499 } else {
2500 upGestureIdBits.value =
2501 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2502 }
2503 while (!upGestureIdBits.isEmpty()) {
2504 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2505
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002506 dispatchMotion(when, readTime, policyFlags, mSource,
2507 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState,
2508 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 mPointerGesture.lastGestureCoords,
2510 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2511 0, mPointerGesture.downTime);
2512
2513 dispatchedGestureIdBits.clearBit(id);
2514 }
2515 }
2516 }
2517
2518 // Send motion events for all pointers that moved.
2519 if (moveNeeded) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002520 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
2521 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 mPointerGesture.currentGestureProperties,
2523 mPointerGesture.currentGestureCoords,
2524 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2525 mPointerGesture.downTime);
2526 }
2527
2528 // Send motion events for all pointers that went down.
2529 if (down) {
2530 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2531 ~dispatchedGestureIdBits.value);
2532 while (!downGestureIdBits.isEmpty()) {
2533 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2534 dispatchedGestureIdBits.markBit(id);
2535
2536 if (dispatchedGestureIdBits.count() == 1) {
2537 mPointerGesture.downTime = when;
2538 }
2539
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002540 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2541 0, 0, metaState, buttonState, 0,
2542 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002543 mPointerGesture.currentGestureCoords,
2544 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2545 0, mPointerGesture.downTime);
2546 }
2547 }
2548
2549 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002550 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002551 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2552 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 mPointerGesture.currentGestureProperties,
2554 mPointerGesture.currentGestureCoords,
2555 mPointerGesture.currentGestureIdToIndex,
2556 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2557 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2558 // Synthesize a hover move event after all pointers go up to indicate that
2559 // the pointer is hovering again even if the user is not currently touching
2560 // the touch pad. This ensures that a view will receive a fresh hover enter
2561 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002562 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002563
2564 PointerProperties pointerProperties;
2565 pointerProperties.clear();
2566 pointerProperties.id = 0;
2567 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2568
2569 PointerCoords pointerCoords;
2570 pointerCoords.clear();
2571 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2572 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2573
2574 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002575 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
2576 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2577 metaState, buttonState, MotionClassification::NONE,
2578 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2579 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002580 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002581 }
2582
2583 // Update state.
2584 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2585 if (!down) {
2586 mPointerGesture.lastGestureIdBits.clear();
2587 } else {
2588 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2589 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2590 uint32_t id = idBits.clearFirstMarkedBit();
2591 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2592 mPointerGesture.lastGestureProperties[index].copyFrom(
2593 mPointerGesture.currentGestureProperties[index]);
2594 mPointerGesture.lastGestureCoords[index].copyFrom(
2595 mPointerGesture.currentGestureCoords[index]);
2596 mPointerGesture.lastGestureIdToIndex[id] = index;
2597 }
2598 }
2599}
2600
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002601void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002602 // Cancel previously dispatches pointers.
2603 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2604 int32_t metaState = getContext()->getGlobalMetaState();
2605 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002606 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2607 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002608 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2609 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2610 0, 0, mPointerGesture.downTime);
2611 }
2612
2613 // Reset the current pointer gesture.
2614 mPointerGesture.reset();
2615 mPointerVelocityControl.reset();
2616
2617 // Remove any current spots.
2618 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002619 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002620 mPointerController->clearSpots();
2621 }
2622}
2623
2624bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2625 bool* outFinishPreviousGesture, bool isTimeout) {
2626 *outCancelPreviousGesture = false;
2627 *outFinishPreviousGesture = false;
2628
2629 // Handle TAP timeout.
2630 if (isTimeout) {
2631#if DEBUG_GESTURES
2632 ALOGD("Gestures: Processing timeout");
2633#endif
2634
Michael Wright227c5542020-07-02 18:30:52 +01002635 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002636 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2637 // The tap/drag timeout has not yet expired.
2638 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2639 mConfig.pointerGestureTapDragInterval);
2640 } else {
2641 // The tap is finished.
2642#if DEBUG_GESTURES
2643 ALOGD("Gestures: TAP finished");
2644#endif
2645 *outFinishPreviousGesture = true;
2646
2647 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002648 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002649 mPointerGesture.currentGestureIdBits.clear();
2650
2651 mPointerVelocityControl.reset();
2652 return true;
2653 }
2654 }
2655
2656 // We did not handle this timeout.
2657 return false;
2658 }
2659
2660 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2661 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2662
2663 // Update the velocity tracker.
2664 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002665 std::vector<VelocityTracker::Position> positions;
2666 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002667 uint32_t id = idBits.clearFirstMarkedBit();
2668 const RawPointerData::Pointer& pointer =
2669 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002670 float x = pointer.x * mPointerXMovementScale;
2671 float y = pointer.y * mPointerYMovementScale;
2672 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002673 }
2674 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2675 positions);
2676 }
2677
2678 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2679 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002680 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2681 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2682 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002683 mPointerGesture.resetTap();
2684 }
2685
2686 // Pick a new active touch id if needed.
2687 // Choose an arbitrary pointer that just went down, if there is one.
2688 // Otherwise choose an arbitrary remaining pointer.
2689 // This guarantees we always have an active touch id when there is at least one pointer.
2690 // We keep the same active touch id for as long as possible.
2691 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2692 int32_t activeTouchId = lastActiveTouchId;
2693 if (activeTouchId < 0) {
2694 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2695 activeTouchId = mPointerGesture.activeTouchId =
2696 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2697 mPointerGesture.firstTouchTime = when;
2698 }
2699 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2700 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2701 activeTouchId = mPointerGesture.activeTouchId =
2702 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2703 } else {
2704 activeTouchId = mPointerGesture.activeTouchId = -1;
2705 }
2706 }
2707
2708 // Determine whether we are in quiet time.
2709 bool isQuietTime = false;
2710 if (activeTouchId < 0) {
2711 mPointerGesture.resetQuietTime();
2712 } else {
2713 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2714 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002715 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2716 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2717 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002718 currentFingerCount < 2) {
2719 // Enter quiet time when exiting swipe or freeform state.
2720 // This is to prevent accidentally entering the hover state and flinging the
2721 // pointer when finishing a swipe and there is still one pointer left onscreen.
2722 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002723 } else if (mPointerGesture.lastGestureMode ==
2724 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002725 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2726 // Enter quiet time when releasing the button and there are still two or more
2727 // fingers down. This may indicate that one finger was used to press the button
2728 // but it has not gone up yet.
2729 isQuietTime = true;
2730 }
2731 if (isQuietTime) {
2732 mPointerGesture.quietTime = when;
2733 }
2734 }
2735 }
2736
2737 // Switch states based on button and pointer state.
2738 if (isQuietTime) {
2739 // Case 1: Quiet time. (QUIET)
2740#if DEBUG_GESTURES
2741 ALOGD("Gestures: QUIET for next %0.3fms",
2742 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2743#endif
Michael Wright227c5542020-07-02 18:30:52 +01002744 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002745 *outFinishPreviousGesture = true;
2746 }
2747
2748 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002749 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002750 mPointerGesture.currentGestureIdBits.clear();
2751
2752 mPointerVelocityControl.reset();
2753 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2754 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2755 // The pointer follows the active touch point.
2756 // Emit DOWN, MOVE, UP events at the pointer location.
2757 //
2758 // Only the active touch matters; other fingers are ignored. This policy helps
2759 // to handle the case where the user places a second finger on the touch pad
2760 // to apply the necessary force to depress an integrated button below the surface.
2761 // We don't want the second finger to be delivered to applications.
2762 //
2763 // For this to work well, we need to make sure to track the pointer that is really
2764 // active. If the user first puts one finger down to click then adds another
2765 // finger to drag then the active pointer should switch to the finger that is
2766 // being dragged.
2767#if DEBUG_GESTURES
2768 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2769 "currentFingerCount=%d",
2770 activeTouchId, currentFingerCount);
2771#endif
2772 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002773 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002774 *outFinishPreviousGesture = true;
2775 mPointerGesture.activeGestureId = 0;
2776 }
2777
2778 // Switch pointers if needed.
2779 // Find the fastest pointer and follow it.
2780 if (activeTouchId >= 0 && currentFingerCount > 1) {
2781 int32_t bestId = -1;
2782 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2783 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2784 uint32_t id = idBits.clearFirstMarkedBit();
2785 float vx, vy;
2786 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2787 float speed = hypotf(vx, vy);
2788 if (speed > bestSpeed) {
2789 bestId = id;
2790 bestSpeed = speed;
2791 }
2792 }
2793 }
2794 if (bestId >= 0 && bestId != activeTouchId) {
2795 mPointerGesture.activeTouchId = activeTouchId = bestId;
2796#if DEBUG_GESTURES
2797 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2798 "bestId=%d, bestSpeed=%0.3f",
2799 bestId, bestSpeed);
2800#endif
2801 }
2802 }
2803
2804 float deltaX = 0, deltaY = 0;
2805 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2806 const RawPointerData::Pointer& currentPointer =
2807 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2808 const RawPointerData::Pointer& lastPointer =
2809 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2810 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2811 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2812
2813 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2814 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2815
2816 // Move the pointer using a relative motion.
2817 // When using spots, the click will occur at the position of the anchor
2818 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002819 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002820 } else {
2821 mPointerVelocityControl.reset();
2822 }
2823
Prabir Pradhand7482e72021-03-09 13:54:55 -08002824 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825
Michael Wright227c5542020-07-02 18:30:52 +01002826 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002827 mPointerGesture.currentGestureIdBits.clear();
2828 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2829 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2830 mPointerGesture.currentGestureProperties[0].clear();
2831 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2832 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2833 mPointerGesture.currentGestureCoords[0].clear();
2834 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2835 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2836 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2837 } else if (currentFingerCount == 0) {
2838 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002839 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002840 *outFinishPreviousGesture = true;
2841 }
2842
2843 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2844 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2845 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002846 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2847 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002848 lastFingerCount == 1) {
2849 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002850 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002851 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2852 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2853#if DEBUG_GESTURES
2854 ALOGD("Gestures: TAP");
2855#endif
2856
2857 mPointerGesture.tapUpTime = when;
2858 getContext()->requestTimeoutAtTime(when +
2859 mConfig.pointerGestureTapDragInterval);
2860
2861 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002862 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002863 mPointerGesture.currentGestureIdBits.clear();
2864 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2865 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2866 mPointerGesture.currentGestureProperties[0].clear();
2867 mPointerGesture.currentGestureProperties[0].id =
2868 mPointerGesture.activeGestureId;
2869 mPointerGesture.currentGestureProperties[0].toolType =
2870 AMOTION_EVENT_TOOL_TYPE_FINGER;
2871 mPointerGesture.currentGestureCoords[0].clear();
2872 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2873 mPointerGesture.tapX);
2874 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2875 mPointerGesture.tapY);
2876 mPointerGesture.currentGestureCoords[0]
2877 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2878
2879 tapped = true;
2880 } else {
2881#if DEBUG_GESTURES
2882 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2883 y - mPointerGesture.tapY);
2884#endif
2885 }
2886 } else {
2887#if DEBUG_GESTURES
2888 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2889 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2890 (when - mPointerGesture.tapDownTime) * 0.000001f);
2891 } else {
2892 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2893 }
2894#endif
2895 }
2896 }
2897
2898 mPointerVelocityControl.reset();
2899
2900 if (!tapped) {
2901#if DEBUG_GESTURES
2902 ALOGD("Gestures: NEUTRAL");
2903#endif
2904 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002905 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906 mPointerGesture.currentGestureIdBits.clear();
2907 }
2908 } else if (currentFingerCount == 1) {
2909 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2910 // The pointer follows the active touch point.
2911 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2912 // When in TAP_DRAG, emit MOVE events at the pointer location.
2913 ALOG_ASSERT(activeTouchId >= 0);
2914
Michael Wright227c5542020-07-02 18:30:52 +01002915 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2916 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002917 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002918 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2920 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002921 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 } else {
2923#if DEBUG_GESTURES
2924 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2925 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2926#endif
2927 }
2928 } else {
2929#if DEBUG_GESTURES
2930 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2931 (when - mPointerGesture.tapUpTime) * 0.000001f);
2932#endif
2933 }
Michael Wright227c5542020-07-02 18:30:52 +01002934 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2935 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002936 }
2937
2938 float deltaX = 0, deltaY = 0;
2939 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2940 const RawPointerData::Pointer& currentPointer =
2941 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2942 const RawPointerData::Pointer& lastPointer =
2943 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2944 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2945 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2946
2947 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2948 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2949
2950 // Move the pointer using a relative motion.
2951 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002952 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002953 } else {
2954 mPointerVelocityControl.reset();
2955 }
2956
2957 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002958 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002959#if DEBUG_GESTURES
2960 ALOGD("Gestures: TAP_DRAG");
2961#endif
2962 down = true;
2963 } else {
2964#if DEBUG_GESTURES
2965 ALOGD("Gestures: HOVER");
2966#endif
Michael Wright227c5542020-07-02 18:30:52 +01002967 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 *outFinishPreviousGesture = true;
2969 }
2970 mPointerGesture.activeGestureId = 0;
2971 down = false;
2972 }
2973
Prabir Pradhand7482e72021-03-09 13:54:55 -08002974 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002975
2976 mPointerGesture.currentGestureIdBits.clear();
2977 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2978 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2979 mPointerGesture.currentGestureProperties[0].clear();
2980 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2981 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2982 mPointerGesture.currentGestureCoords[0].clear();
2983 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2984 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2985 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2986 down ? 1.0f : 0.0f);
2987
2988 if (lastFingerCount == 0 && currentFingerCount != 0) {
2989 mPointerGesture.resetTap();
2990 mPointerGesture.tapDownTime = when;
2991 mPointerGesture.tapX = x;
2992 mPointerGesture.tapY = y;
2993 }
2994 } else {
2995 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2996 // We need to provide feedback for each finger that goes down so we cannot wait
2997 // for the fingers to move before deciding what to do.
2998 //
2999 // The ambiguous case is deciding what to do when there are two fingers down but they
3000 // have not moved enough to determine whether they are part of a drag or part of a
3001 // freeform gesture, or just a press or long-press at the pointer location.
3002 //
3003 // When there are two fingers we start with the PRESS hypothesis and we generate a
3004 // down at the pointer location.
3005 //
3006 // When the two fingers move enough or when additional fingers are added, we make
3007 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3008 ALOG_ASSERT(activeTouchId >= 0);
3009
3010 bool settled = when >=
3011 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003012 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3013 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3014 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003015 *outFinishPreviousGesture = true;
3016 } else if (!settled && currentFingerCount > lastFingerCount) {
3017 // Additional pointers have gone down but not yet settled.
3018 // Reset the gesture.
3019#if DEBUG_GESTURES
3020 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3021 "settle time remaining %0.3fms",
3022 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3023 when) * 0.000001f);
3024#endif
3025 *outCancelPreviousGesture = true;
3026 } else {
3027 // Continue previous gesture.
3028 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3029 }
3030
3031 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003032 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003033 mPointerGesture.activeGestureId = 0;
3034 mPointerGesture.referenceIdBits.clear();
3035 mPointerVelocityControl.reset();
3036
3037 // Use the centroid and pointer location as the reference points for the gesture.
3038#if DEBUG_GESTURES
3039 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3040 "settle time remaining %0.3fms",
3041 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3042 when) * 0.000001f);
3043#endif
3044 mCurrentRawState.rawPointerData
3045 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3046 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003047 auto [x, y] = getMouseCursorPosition();
3048 mPointerGesture.referenceGestureX = x;
3049 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003050 }
3051
3052 // Clear the reference deltas for fingers not yet included in the reference calculation.
3053 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3054 ~mPointerGesture.referenceIdBits.value);
3055 !idBits.isEmpty();) {
3056 uint32_t id = idBits.clearFirstMarkedBit();
3057 mPointerGesture.referenceDeltas[id].dx = 0;
3058 mPointerGesture.referenceDeltas[id].dy = 0;
3059 }
3060 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3061
3062 // Add delta for all fingers and calculate a common movement delta.
3063 float commonDeltaX = 0, commonDeltaY = 0;
3064 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3065 mCurrentCookedState.fingerIdBits.value);
3066 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3067 bool first = (idBits == commonIdBits);
3068 uint32_t id = idBits.clearFirstMarkedBit();
3069 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3070 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3071 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3072 delta.dx += cpd.x - lpd.x;
3073 delta.dy += cpd.y - lpd.y;
3074
3075 if (first) {
3076 commonDeltaX = delta.dx;
3077 commonDeltaY = delta.dy;
3078 } else {
3079 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3080 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3081 }
3082 }
3083
3084 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003085 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003086 float dist[MAX_POINTER_ID + 1];
3087 int32_t distOverThreshold = 0;
3088 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3089 uint32_t id = idBits.clearFirstMarkedBit();
3090 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3091 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3092 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3093 distOverThreshold += 1;
3094 }
3095 }
3096
3097 // Only transition when at least two pointers have moved further than
3098 // the minimum distance threshold.
3099 if (distOverThreshold >= 2) {
3100 if (currentFingerCount > 2) {
3101 // There are more than two pointers, switch to FREEFORM.
3102#if DEBUG_GESTURES
3103 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3104 currentFingerCount);
3105#endif
3106 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003107 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003108 } else {
3109 // There are exactly two pointers.
3110 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3111 uint32_t id1 = idBits.clearFirstMarkedBit();
3112 uint32_t id2 = idBits.firstMarkedBit();
3113 const RawPointerData::Pointer& p1 =
3114 mCurrentRawState.rawPointerData.pointerForId(id1);
3115 const RawPointerData::Pointer& p2 =
3116 mCurrentRawState.rawPointerData.pointerForId(id2);
3117 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3118 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3119 // There are two pointers but they are too far apart for a SWIPE,
3120 // switch to FREEFORM.
3121#if DEBUG_GESTURES
3122 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3123 mutualDistance, mPointerGestureMaxSwipeWidth);
3124#endif
3125 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003126 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003127 } else {
3128 // There are two pointers. Wait for both pointers to start moving
3129 // before deciding whether this is a SWIPE or FREEFORM gesture.
3130 float dist1 = dist[id1];
3131 float dist2 = dist[id2];
3132 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3133 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3134 // Calculate the dot product of the displacement vectors.
3135 // When the vectors are oriented in approximately the same direction,
3136 // the angle betweeen them is near zero and the cosine of the angle
3137 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3138 // mag(v2).
3139 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3140 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3141 float dx1 = delta1.dx * mPointerXZoomScale;
3142 float dy1 = delta1.dy * mPointerYZoomScale;
3143 float dx2 = delta2.dx * mPointerXZoomScale;
3144 float dy2 = delta2.dy * mPointerYZoomScale;
3145 float dot = dx1 * dx2 + dy1 * dy2;
3146 float cosine = dot / (dist1 * dist2); // denominator always > 0
3147 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3148 // Pointers are moving in the same direction. Switch to SWIPE.
3149#if DEBUG_GESTURES
3150 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3151 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3152 "cosine %0.3f >= %0.3f",
3153 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3154 mConfig.pointerGestureMultitouchMinDistance, cosine,
3155 mConfig.pointerGestureSwipeTransitionAngleCosine);
3156#endif
Michael Wright227c5542020-07-02 18:30:52 +01003157 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003158 } else {
3159 // Pointers are moving in different directions. Switch to FREEFORM.
3160#if DEBUG_GESTURES
3161 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3162 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3163 "cosine %0.3f < %0.3f",
3164 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3165 mConfig.pointerGestureMultitouchMinDistance, cosine,
3166 mConfig.pointerGestureSwipeTransitionAngleCosine);
3167#endif
3168 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003169 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003170 }
3171 }
3172 }
3173 }
3174 }
Michael Wright227c5542020-07-02 18:30:52 +01003175 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003176 // Switch from SWIPE to FREEFORM if additional pointers go down.
3177 // Cancel previous gesture.
3178 if (currentFingerCount > 2) {
3179#if DEBUG_GESTURES
3180 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3181 currentFingerCount);
3182#endif
3183 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003184 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003185 }
3186 }
3187
3188 // Move the reference points based on the overall group motion of the fingers
3189 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003190 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003191 (commonDeltaX || commonDeltaY)) {
3192 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3193 uint32_t id = idBits.clearFirstMarkedBit();
3194 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3195 delta.dx = 0;
3196 delta.dy = 0;
3197 }
3198
3199 mPointerGesture.referenceTouchX += commonDeltaX;
3200 mPointerGesture.referenceTouchY += commonDeltaY;
3201
3202 commonDeltaX *= mPointerXMovementScale;
3203 commonDeltaY *= mPointerYMovementScale;
3204
3205 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3206 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3207
3208 mPointerGesture.referenceGestureX += commonDeltaX;
3209 mPointerGesture.referenceGestureY += commonDeltaY;
3210 }
3211
3212 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003213 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3214 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003215 // PRESS or SWIPE mode.
3216#if DEBUG_GESTURES
3217 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3218 "activeGestureId=%d, currentTouchPointerCount=%d",
3219 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3220#endif
3221 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3222
3223 mPointerGesture.currentGestureIdBits.clear();
3224 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3225 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3226 mPointerGesture.currentGestureProperties[0].clear();
3227 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3228 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3229 mPointerGesture.currentGestureCoords[0].clear();
3230 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3231 mPointerGesture.referenceGestureX);
3232 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3233 mPointerGesture.referenceGestureY);
3234 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003235 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003236 // FREEFORM mode.
3237#if DEBUG_GESTURES
3238 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3239 "activeGestureId=%d, currentTouchPointerCount=%d",
3240 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3241#endif
3242 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3243
3244 mPointerGesture.currentGestureIdBits.clear();
3245
3246 BitSet32 mappedTouchIdBits;
3247 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003248 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003249 // Initially, assign the active gesture id to the active touch point
3250 // if there is one. No other touch id bits are mapped yet.
3251 if (!*outCancelPreviousGesture) {
3252 mappedTouchIdBits.markBit(activeTouchId);
3253 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3254 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3255 mPointerGesture.activeGestureId;
3256 } else {
3257 mPointerGesture.activeGestureId = -1;
3258 }
3259 } else {
3260 // Otherwise, assume we mapped all touches from the previous frame.
3261 // Reuse all mappings that are still applicable.
3262 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3263 mCurrentCookedState.fingerIdBits.value;
3264 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3265
3266 // Check whether we need to choose a new active gesture id because the
3267 // current went went up.
3268 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3269 ~mCurrentCookedState.fingerIdBits.value);
3270 !upTouchIdBits.isEmpty();) {
3271 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3272 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3273 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3274 mPointerGesture.activeGestureId = -1;
3275 break;
3276 }
3277 }
3278 }
3279
3280#if DEBUG_GESTURES
3281 ALOGD("Gestures: FREEFORM follow up "
3282 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3283 "activeGestureId=%d",
3284 mappedTouchIdBits.value, usedGestureIdBits.value,
3285 mPointerGesture.activeGestureId);
3286#endif
3287
3288 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3289 for (uint32_t i = 0; i < currentFingerCount; i++) {
3290 uint32_t touchId = idBits.clearFirstMarkedBit();
3291 uint32_t gestureId;
3292 if (!mappedTouchIdBits.hasBit(touchId)) {
3293 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3294 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3295#if DEBUG_GESTURES
3296 ALOGD("Gestures: FREEFORM "
3297 "new mapping for touch id %d -> gesture id %d",
3298 touchId, gestureId);
3299#endif
3300 } else {
3301 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3302#if DEBUG_GESTURES
3303 ALOGD("Gestures: FREEFORM "
3304 "existing mapping for touch id %d -> gesture id %d",
3305 touchId, gestureId);
3306#endif
3307 }
3308 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3309 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3310
3311 const RawPointerData::Pointer& pointer =
3312 mCurrentRawState.rawPointerData.pointerForId(touchId);
3313 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3314 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3315 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3316
3317 mPointerGesture.currentGestureProperties[i].clear();
3318 mPointerGesture.currentGestureProperties[i].id = gestureId;
3319 mPointerGesture.currentGestureProperties[i].toolType =
3320 AMOTION_EVENT_TOOL_TYPE_FINGER;
3321 mPointerGesture.currentGestureCoords[i].clear();
3322 mPointerGesture.currentGestureCoords[i]
3323 .setAxisValue(AMOTION_EVENT_AXIS_X,
3324 mPointerGesture.referenceGestureX + deltaX);
3325 mPointerGesture.currentGestureCoords[i]
3326 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3327 mPointerGesture.referenceGestureY + deltaY);
3328 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3329 1.0f);
3330 }
3331
3332 if (mPointerGesture.activeGestureId < 0) {
3333 mPointerGesture.activeGestureId =
3334 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3335#if DEBUG_GESTURES
3336 ALOGD("Gestures: FREEFORM new "
3337 "activeGestureId=%d",
3338 mPointerGesture.activeGestureId);
3339#endif
3340 }
3341 }
3342 }
3343
3344 mPointerController->setButtonState(mCurrentRawState.buttonState);
3345
3346#if DEBUG_GESTURES
3347 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3348 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3349 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3350 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3351 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3352 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3353 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3354 uint32_t id = idBits.clearFirstMarkedBit();
3355 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3356 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3357 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3358 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3359 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3360 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3361 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3362 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3363 }
3364 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3365 uint32_t id = idBits.clearFirstMarkedBit();
3366 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3367 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3368 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3369 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3370 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3371 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3372 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3373 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3374 }
3375#endif
3376 return true;
3377}
3378
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003379void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003380 mPointerSimple.currentCoords.clear();
3381 mPointerSimple.currentProperties.clear();
3382
3383 bool down, hovering;
3384 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3385 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3386 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003387 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3388 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003389
3390 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3391 down = !hovering;
3392
Prabir Pradhand7482e72021-03-09 13:54:55 -08003393 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003394 mPointerSimple.currentCoords.copyFrom(
3395 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3396 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3397 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3398 mPointerSimple.currentProperties.id = 0;
3399 mPointerSimple.currentProperties.toolType =
3400 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3401 } else {
3402 down = false;
3403 hovering = false;
3404 }
3405
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003406 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003407}
3408
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003409void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3410 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003411}
3412
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003413void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003414 mPointerSimple.currentCoords.clear();
3415 mPointerSimple.currentProperties.clear();
3416
3417 bool down, hovering;
3418 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3419 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3420 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3421 float deltaX = 0, deltaY = 0;
3422 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3423 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3424 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3425 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3426 mPointerXMovementScale;
3427 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3428 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3429 mPointerYMovementScale;
3430
3431 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3432 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3433
Prabir Pradhand7482e72021-03-09 13:54:55 -08003434 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003435 } else {
3436 mPointerVelocityControl.reset();
3437 }
3438
3439 down = isPointerDown(mCurrentRawState.buttonState);
3440 hovering = !down;
3441
Prabir Pradhand7482e72021-03-09 13:54:55 -08003442 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003443 mPointerSimple.currentCoords.copyFrom(
3444 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3445 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3446 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3447 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3448 hovering ? 0.0f : 1.0f);
3449 mPointerSimple.currentProperties.id = 0;
3450 mPointerSimple.currentProperties.toolType =
3451 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3452 } else {
3453 mPointerVelocityControl.reset();
3454
3455 down = false;
3456 hovering = false;
3457 }
3458
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003459 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003460}
3461
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003462void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3463 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003464
3465 mPointerVelocityControl.reset();
3466}
3467
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003468void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3469 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003470 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003471
3472 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003473 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003474 mPointerController->clearSpots();
3475 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003476 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003477 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003478 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003479 }
Garfield Tan9514d782020-11-10 16:37:23 -08003480 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003481
Prabir Pradhand7482e72021-03-09 13:54:55 -08003482 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003483
3484 if (mPointerSimple.down && !down) {
3485 mPointerSimple.down = false;
3486
3487 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003488 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3489 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003490 mLastRawState.buttonState, MotionClassification::NONE,
3491 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3492 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3493 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3494 /* videoFrames */ {});
3495 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003496 }
3497
3498 if (mPointerSimple.hovering && !hovering) {
3499 mPointerSimple.hovering = false;
3500
3501 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003502 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3503 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3504 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003505 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3506 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3507 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3508 /* videoFrames */ {});
3509 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003510 }
3511
3512 if (down) {
3513 if (!mPointerSimple.down) {
3514 mPointerSimple.down = true;
3515 mPointerSimple.downTime = when;
3516
3517 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003518 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003519 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3520 metaState, mCurrentRawState.buttonState,
3521 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3522 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3523 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3524 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3525 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003526 }
3527
3528 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003529 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3530 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003531 mCurrentRawState.buttonState, MotionClassification::NONE,
3532 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3533 &mPointerSimple.currentCoords, mOrientedXPrecision,
3534 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3535 mPointerSimple.downTime, /* videoFrames */ {});
3536 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003537 }
3538
3539 if (hovering) {
3540 if (!mPointerSimple.hovering) {
3541 mPointerSimple.hovering = true;
3542
3543 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003544 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003545 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3546 metaState, mCurrentRawState.buttonState,
3547 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3548 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3549 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3550 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3551 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003552 }
3553
3554 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003555 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3556 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3557 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003558 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3559 &mPointerSimple.currentCoords, mOrientedXPrecision,
3560 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3561 mPointerSimple.downTime, /* videoFrames */ {});
3562 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 }
3564
3565 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3566 float vscroll = mCurrentRawState.rawVScroll;
3567 float hscroll = mCurrentRawState.rawHScroll;
3568 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3569 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3570
3571 // Send scroll.
3572 PointerCoords pointerCoords;
3573 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3574 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3575 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3576
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003577 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3578 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003579 mCurrentRawState.buttonState, MotionClassification::NONE,
3580 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3581 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3582 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3583 /* videoFrames */ {});
3584 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003585 }
3586
3587 // Save state.
3588 if (down || hovering) {
3589 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3590 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3591 } else {
3592 mPointerSimple.reset();
3593 }
3594}
3595
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003596void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003597 mPointerSimple.currentCoords.clear();
3598 mPointerSimple.currentProperties.clear();
3599
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003600 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003601}
3602
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003603void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3604 uint32_t source, int32_t action, int32_t actionButton,
3605 int32_t flags, int32_t metaState, int32_t buttonState,
3606 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003607 const PointerCoords* coords, const uint32_t* idToIndex,
3608 BitSet32 idBits, int32_t changedId, float xPrecision,
3609 float yPrecision, nsecs_t downTime) {
3610 PointerCoords pointerCoords[MAX_POINTERS];
3611 PointerProperties pointerProperties[MAX_POINTERS];
3612 uint32_t pointerCount = 0;
3613 while (!idBits.isEmpty()) {
3614 uint32_t id = idBits.clearFirstMarkedBit();
3615 uint32_t index = idToIndex[id];
3616 pointerProperties[pointerCount].copyFrom(properties[index]);
3617 pointerCoords[pointerCount].copyFrom(coords[index]);
3618
3619 if (changedId >= 0 && id == uint32_t(changedId)) {
3620 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3621 }
3622
3623 pointerCount += 1;
3624 }
3625
3626 ALOG_ASSERT(pointerCount != 0);
3627
3628 if (changedId >= 0 && pointerCount == 1) {
3629 // Replace initial down and final up action.
3630 // We can compare the action without masking off the changed pointer index
3631 // because we know the index is 0.
3632 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3633 action = AMOTION_EVENT_ACTION_DOWN;
3634 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003635 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3636 action = AMOTION_EVENT_ACTION_CANCEL;
3637 } else {
3638 action = AMOTION_EVENT_ACTION_UP;
3639 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003640 } else {
3641 // Can't happen.
3642 ALOG_ASSERT(false);
3643 }
3644 }
3645 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3646 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003647 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003648 auto [x, y] = getMouseCursorPosition();
3649 xCursorPosition = x;
3650 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003651 }
3652 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3653 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003654 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003655 std::for_each(frames.begin(), frames.end(),
3656 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003657 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3658 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003659 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3660 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3661 downTime, std::move(frames));
3662 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003663}
3664
3665bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3666 const PointerCoords* inCoords,
3667 const uint32_t* inIdToIndex,
3668 PointerProperties* outProperties,
3669 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3670 BitSet32 idBits) const {
3671 bool changed = false;
3672 while (!idBits.isEmpty()) {
3673 uint32_t id = idBits.clearFirstMarkedBit();
3674 uint32_t inIndex = inIdToIndex[id];
3675 uint32_t outIndex = outIdToIndex[id];
3676
3677 const PointerProperties& curInProperties = inProperties[inIndex];
3678 const PointerCoords& curInCoords = inCoords[inIndex];
3679 PointerProperties& curOutProperties = outProperties[outIndex];
3680 PointerCoords& curOutCoords = outCoords[outIndex];
3681
3682 if (curInProperties != curOutProperties) {
3683 curOutProperties.copyFrom(curInProperties);
3684 changed = true;
3685 }
3686
3687 if (curInCoords != curOutCoords) {
3688 curOutCoords.copyFrom(curInCoords);
3689 changed = true;
3690 }
3691 }
3692 return changed;
3693}
3694
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003695void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3696 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3697 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003698}
3699
Arthur Hung4197f6b2020-03-16 15:39:59 +08003700// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003701void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003702 // Scale to surface coordinate.
3703 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3704 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3705
arthurhunga36b28e2020-12-29 20:28:15 +08003706 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3707 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3708
Arthur Hung4197f6b2020-03-16 15:39:59 +08003709 // Rotate to surface coordinate.
3710 // 0 - no swap and reverse.
3711 // 90 - swap x/y and reverse y.
3712 // 180 - reverse x, y.
3713 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003714 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003715 case DISPLAY_ORIENTATION_0:
3716 x = xScaled + mXTranslate;
3717 y = yScaled + mYTranslate;
3718 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003719 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003720 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003721 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003722 break;
3723 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003724 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3725 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003726 break;
3727 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003728 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003729 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003730 break;
3731 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003732 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003733 }
3734}
3735
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003736bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003737 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3738 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3739
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003740 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003741 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003742 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003743 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003744}
3745
3746const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3747 for (const VirtualKey& virtualKey : mVirtualKeys) {
3748#if DEBUG_VIRTUAL_KEYS
3749 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3750 "left=%d, top=%d, right=%d, bottom=%d",
3751 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3752 virtualKey.hitRight, virtualKey.hitBottom);
3753#endif
3754
3755 if (virtualKey.isHit(x, y)) {
3756 return &virtualKey;
3757 }
3758 }
3759
3760 return nullptr;
3761}
3762
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003763void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3764 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3765 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003766
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003767 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003768
3769 if (currentPointerCount == 0) {
3770 // No pointers to assign.
3771 return;
3772 }
3773
3774 if (lastPointerCount == 0) {
3775 // All pointers are new.
3776 for (uint32_t i = 0; i < currentPointerCount; i++) {
3777 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003778 current.rawPointerData.pointers[i].id = id;
3779 current.rawPointerData.idToIndex[id] = i;
3780 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003781 }
3782 return;
3783 }
3784
3785 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003786 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003787 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003788 uint32_t id = last.rawPointerData.pointers[0].id;
3789 current.rawPointerData.pointers[0].id = id;
3790 current.rawPointerData.idToIndex[id] = 0;
3791 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003792 return;
3793 }
3794
3795 // General case.
3796 // We build a heap of squared euclidean distances between current and last pointers
3797 // associated with the current and last pointer indices. Then, we find the best
3798 // match (by distance) for each current pointer.
3799 // The pointers must have the same tool type but it is possible for them to
3800 // transition from hovering to touching or vice-versa while retaining the same id.
3801 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3802
3803 uint32_t heapSize = 0;
3804 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3805 currentPointerIndex++) {
3806 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3807 lastPointerIndex++) {
3808 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003809 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003810 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003811 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003812 if (currentPointer.toolType == lastPointer.toolType) {
3813 int64_t deltaX = currentPointer.x - lastPointer.x;
3814 int64_t deltaY = currentPointer.y - lastPointer.y;
3815
3816 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3817
3818 // Insert new element into the heap (sift up).
3819 heap[heapSize].currentPointerIndex = currentPointerIndex;
3820 heap[heapSize].lastPointerIndex = lastPointerIndex;
3821 heap[heapSize].distance = distance;
3822 heapSize += 1;
3823 }
3824 }
3825 }
3826
3827 // Heapify
3828 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3829 startIndex -= 1;
3830 for (uint32_t parentIndex = startIndex;;) {
3831 uint32_t childIndex = parentIndex * 2 + 1;
3832 if (childIndex >= heapSize) {
3833 break;
3834 }
3835
3836 if (childIndex + 1 < heapSize &&
3837 heap[childIndex + 1].distance < heap[childIndex].distance) {
3838 childIndex += 1;
3839 }
3840
3841 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3842 break;
3843 }
3844
3845 swap(heap[parentIndex], heap[childIndex]);
3846 parentIndex = childIndex;
3847 }
3848 }
3849
3850#if DEBUG_POINTER_ASSIGNMENT
3851 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3852 for (size_t i = 0; i < heapSize; i++) {
3853 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3854 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3855 }
3856#endif
3857
3858 // Pull matches out by increasing order of distance.
3859 // To avoid reassigning pointers that have already been matched, the loop keeps track
3860 // of which last and current pointers have been matched using the matchedXXXBits variables.
3861 // It also tracks the used pointer id bits.
3862 BitSet32 matchedLastBits(0);
3863 BitSet32 matchedCurrentBits(0);
3864 BitSet32 usedIdBits(0);
3865 bool first = true;
3866 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3867 while (heapSize > 0) {
3868 if (first) {
3869 // The first time through the loop, we just consume the root element of
3870 // the heap (the one with smallest distance).
3871 first = false;
3872 } else {
3873 // Previous iterations consumed the root element of the heap.
3874 // Pop root element off of the heap (sift down).
3875 heap[0] = heap[heapSize];
3876 for (uint32_t parentIndex = 0;;) {
3877 uint32_t childIndex = parentIndex * 2 + 1;
3878 if (childIndex >= heapSize) {
3879 break;
3880 }
3881
3882 if (childIndex + 1 < heapSize &&
3883 heap[childIndex + 1].distance < heap[childIndex].distance) {
3884 childIndex += 1;
3885 }
3886
3887 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3888 break;
3889 }
3890
3891 swap(heap[parentIndex], heap[childIndex]);
3892 parentIndex = childIndex;
3893 }
3894
3895#if DEBUG_POINTER_ASSIGNMENT
3896 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003897 for (size_t j = 0; j < heapSize; j++) {
3898 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3899 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003900 }
3901#endif
3902 }
3903
3904 heapSize -= 1;
3905
3906 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3907 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3908
3909 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3910 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3911
3912 matchedCurrentBits.markBit(currentPointerIndex);
3913 matchedLastBits.markBit(lastPointerIndex);
3914
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003915 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3916 current.rawPointerData.pointers[currentPointerIndex].id = id;
3917 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3918 current.rawPointerData.markIdBit(id,
3919 current.rawPointerData.isHovering(
3920 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003921 usedIdBits.markBit(id);
3922
3923#if DEBUG_POINTER_ASSIGNMENT
3924 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3925 ", distance=%" PRIu64,
3926 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3927#endif
3928 break;
3929 }
3930 }
3931
3932 // Assign fresh ids to pointers that were not matched in the process.
3933 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3934 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3935 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3936
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003937 current.rawPointerData.pointers[currentPointerIndex].id = id;
3938 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3939 current.rawPointerData.markIdBit(id,
3940 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003941
3942#if DEBUG_POINTER_ASSIGNMENT
3943 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3944#endif
3945 }
3946}
3947
3948int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3949 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3950 return AKEY_STATE_VIRTUAL;
3951 }
3952
3953 for (const VirtualKey& virtualKey : mVirtualKeys) {
3954 if (virtualKey.keyCode == keyCode) {
3955 return AKEY_STATE_UP;
3956 }
3957 }
3958
3959 return AKEY_STATE_UNKNOWN;
3960}
3961
3962int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3963 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3964 return AKEY_STATE_VIRTUAL;
3965 }
3966
3967 for (const VirtualKey& virtualKey : mVirtualKeys) {
3968 if (virtualKey.scanCode == scanCode) {
3969 return AKEY_STATE_UP;
3970 }
3971 }
3972
3973 return AKEY_STATE_UNKNOWN;
3974}
3975
3976bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3977 const int32_t* keyCodes, uint8_t* outFlags) {
3978 for (const VirtualKey& virtualKey : mVirtualKeys) {
3979 for (size_t i = 0; i < numCodes; i++) {
3980 if (virtualKey.keyCode == keyCodes[i]) {
3981 outFlags[i] = 1;
3982 }
3983 }
3984 }
3985
3986 return true;
3987}
3988
3989std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3990 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003991 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003992 return std::make_optional(mPointerController->getDisplayId());
3993 } else {
3994 return std::make_optional(mViewport.displayId);
3995 }
3996 }
3997 return std::nullopt;
3998}
3999
Prabir Pradhand7482e72021-03-09 13:54:55 -08004000void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
4001 if (isPerWindowInputRotationEnabled()) {
4002 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4003 // space that is oriented with the viewport.
4004 rotateDelta(mViewport.orientation, &dx, &dy);
4005 }
4006
4007 mPointerController->move(dx, dy);
4008}
4009
4010std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4011 float x = 0;
4012 float y = 0;
4013 mPointerController->getPosition(&x, &y);
4014
4015 if (!isPerWindowInputRotationEnabled()) return {x, y};
4016 if (!mViewport.isValid()) return {x, y};
4017
4018 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4019 // to InputReader's un-rotated coordinate space.
4020 const int32_t orientation = getInverseRotation(mViewport.orientation);
4021 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4022 return {x, y};
4023}
4024
4025void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4026 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4027 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4028 // coordinate space that is oriented with the viewport.
4029 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4030 }
4031
4032 mPointerController->setPosition(x, y);
4033}
4034
4035void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4036 BitSet32 spotIdBits, int32_t displayId) {
4037 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4038
4039 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4040 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4041 float x = spotCoords[index].getX();
4042 float y = spotCoords[index].getY();
4043 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4044
4045 if (isPerWindowInputRotationEnabled()) {
4046 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4047 // coordinate space.
4048 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4049 }
4050
4051 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4052 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4053 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4054 }
4055
4056 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4057}
4058
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004059} // namespace android