blob: 8733540e53e7cc2cba89784138005df91be708be [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
Chris Yea03dd232020-09-08 19:21:09 -070021#include <input/NamedEnum.h>
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070022#include "TouchInputMapper.h"
23
24#include "CursorButtonAccumulator.h"
25#include "CursorScrollAccumulator.h"
26#include "TouchButtonAccumulator.h"
27#include "TouchCursorInputMapperCommon.h"
28
29namespace android {
30
31// --- Constants ---
32
33// Maximum amount of latency to add to touch events while waiting for data from an
34// external stylus.
35static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
36
37// Maximum amount of time to wait on touch data before pushing out new pressure data.
38static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
39
40// Artificial latency on synthetic events created from stylus data without corresponding touch
41// data.
42static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
43
44// --- Static Definitions ---
45
46template <typename T>
47inline static void swap(T& a, T& b) {
48 T temp = a;
49 a = b;
50 b = temp;
51}
52
53static float calculateCommonVector(float a, float b) {
54 if (a > 0 && b > 0) {
55 return a < b ? a : b;
56 } else if (a < 0 && b < 0) {
57 return a > b ? a : b;
58 } else {
59 return 0;
60 }
61}
62
63inline static float distance(float x1, float y1, float x2, float y2) {
64 return hypotf(x1 - x2, y1 - y2);
65}
66
67inline static int32_t signExtendNybble(int32_t value) {
68 return value >= 8 ? value - 16 : value;
69}
70
71// --- RawPointerAxes ---
72
73RawPointerAxes::RawPointerAxes() {
74 clear();
75}
76
77void RawPointerAxes::clear() {
78 x.clear();
79 y.clear();
80 pressure.clear();
81 touchMajor.clear();
82 touchMinor.clear();
83 toolMajor.clear();
84 toolMinor.clear();
85 orientation.clear();
86 distance.clear();
87 tiltX.clear();
88 tiltY.clear();
89 trackingId.clear();
90 slot.clear();
91}
92
93// --- RawPointerData ---
94
95RawPointerData::RawPointerData() {
96 clear();
97}
98
99void RawPointerData::clear() {
100 pointerCount = 0;
101 clearIdBits();
102}
103
104void RawPointerData::copyFrom(const RawPointerData& other) {
105 pointerCount = other.pointerCount;
106 hoveringIdBits = other.hoveringIdBits;
107 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800108 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109
110 for (uint32_t i = 0; i < pointerCount; i++) {
111 pointers[i] = other.pointers[i];
112
113 int id = pointers[i].id;
114 idToIndex[id] = other.idToIndex[id];
115 }
116}
117
118void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
119 float x = 0, y = 0;
120 uint32_t count = touchingIdBits.count();
121 if (count) {
122 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
123 uint32_t id = idBits.clearFirstMarkedBit();
124 const Pointer& pointer = pointerForId(id);
125 x += pointer.x;
126 y += pointer.y;
127 }
128 x /= count;
129 y /= count;
130 }
131 *outX = x;
132 *outY = y;
133}
134
135// --- CookedPointerData ---
136
137CookedPointerData::CookedPointerData() {
138 clear();
139}
140
141void CookedPointerData::clear() {
142 pointerCount = 0;
143 hoveringIdBits.clear();
144 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800145 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000146 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700147}
148
149void CookedPointerData::copyFrom(const CookedPointerData& other) {
150 pointerCount = other.pointerCount;
151 hoveringIdBits = other.hoveringIdBits;
152 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000153 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700154
155 for (uint32_t i = 0; i < pointerCount; i++) {
156 pointerProperties[i].copyFrom(other.pointerProperties[i]);
157 pointerCoords[i].copyFrom(other.pointerCoords[i]);
158
159 int id = pointerProperties[i].id;
160 idToIndex[id] = other.idToIndex[id];
161 }
162}
163
164// --- TouchInputMapper ---
165
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800166TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
167 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700168 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100169 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800170 mRawSurfaceWidth(-1),
171 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700172 mSurfaceLeft(0),
173 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700174 mSurfaceRight(0),
175 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700176 mPhysicalWidth(-1),
177 mPhysicalHeight(-1),
178 mPhysicalLeft(0),
179 mPhysicalTop(0),
180 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
181
182TouchInputMapper::~TouchInputMapper() {}
183
184uint32_t TouchInputMapper::getSources() {
185 return mSource;
186}
187
188void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
189 InputMapper::populateDeviceInfo(info);
190
Michael Wright227c5542020-07-02 18:30:52 +0100191 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 info->addMotionRange(mOrientedRanges.x);
193 info->addMotionRange(mOrientedRanges.y);
194 info->addMotionRange(mOrientedRanges.pressure);
195
Chris Yef74dc422020-09-02 22:41:50 -0700196 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700197 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
198 //
199 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
200 // motion, i.e. the hardware dimensions, as the finger could move completely across the
201 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700202 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
203 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
204 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
205 x.fuzz, x.resolution);
206 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
207 y.fuzz, y.resolution);
208 }
209
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700210 if (mOrientedRanges.haveSize) {
211 info->addMotionRange(mOrientedRanges.size);
212 }
213
214 if (mOrientedRanges.haveTouchSize) {
215 info->addMotionRange(mOrientedRanges.touchMajor);
216 info->addMotionRange(mOrientedRanges.touchMinor);
217 }
218
219 if (mOrientedRanges.haveToolSize) {
220 info->addMotionRange(mOrientedRanges.toolMajor);
221 info->addMotionRange(mOrientedRanges.toolMinor);
222 }
223
224 if (mOrientedRanges.haveOrientation) {
225 info->addMotionRange(mOrientedRanges.orientation);
226 }
227
228 if (mOrientedRanges.haveDistance) {
229 info->addMotionRange(mOrientedRanges.distance);
230 }
231
232 if (mOrientedRanges.haveTilt) {
233 info->addMotionRange(mOrientedRanges.tilt);
234 }
235
236 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
237 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
238 0.0f);
239 }
240 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
241 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
242 0.0f);
243 }
Michael Wright227c5542020-07-02 18:30:52 +0100244 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700245 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
246 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
247 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
248 x.fuzz, x.resolution);
249 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
250 y.fuzz, y.resolution);
251 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
252 x.fuzz, x.resolution);
253 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
254 y.fuzz, y.resolution);
255 }
256 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
257 }
258}
259
260void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700261 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
262 NamedEnum::string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700263 dumpParameters(dump);
264 dumpVirtualKeys(dump);
265 dumpRawPointerAxes(dump);
266 dumpCalibration(dump);
267 dumpAffineTransformation(dump);
268 dumpSurface(dump);
269
270 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
271 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
272 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
273 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
274 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
275 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
276 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
277 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
278 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
279 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
280 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
281 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
282 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
283 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
284 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
285 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
286 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
287
288 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
289 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
290 mLastRawState.rawPointerData.pointerCount);
291 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
292 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
293 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
294 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
295 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
296 "toolType=%d, isHovering=%s\n",
297 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
298 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
299 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
300 pointer.distance, pointer.toolType, toString(pointer.isHovering));
301 }
302
303 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
304 mLastCookedState.buttonState);
305 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
306 mLastCookedState.cookedPointerData.pointerCount);
307 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
308 const PointerProperties& pointerProperties =
309 mLastCookedState.cookedPointerData.pointerProperties[i];
310 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000311 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
312 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
313 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
315 "toolType=%d, isHovering=%s\n",
316 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
327 pointerProperties.toolType,
328 toString(mLastCookedState.cookedPointerData.isHovering(i)));
329 }
330
331 dump += INDENT3 "Stylus Fusion:\n";
332 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
333 toString(mExternalStylusConnected));
334 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
335 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
336 mExternalStylusFusionTimeout);
337 dump += INDENT3 "External Stylus State:\n";
338 dumpStylusState(dump, mExternalStylusState);
339
Michael Wright227c5542020-07-02 18:30:52 +0100340 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
342 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
343 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
344 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
345 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
346 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
347 }
348}
349
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
351 uint32_t changes) {
352 InputMapper::configure(when, config, changes);
353
354 mConfig = *config;
355
356 if (!changes) { // first time only
357 // Configure basic parameters.
358 configureParameters();
359
360 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mCursorScrollAccumulator.configure(getDeviceContext());
362 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700363
364 // Configure absolute axis information.
365 configureRawPointerAxes();
366
367 // Prepare input device calibration.
368 parseCalibration();
369 resolveCalibration();
370 }
371
372 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
373 // Update location calibration to reflect current settings
374 updateAffineTransformation();
375 }
376
377 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
378 // Update pointer speed.
379 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
380 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
381 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 }
383
384 bool resetNeeded = false;
385 if (!changes ||
386 (changes &
387 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800388 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
390 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
391 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
392 // Configure device sources, surface dimensions, orientation and
393 // scaling factors.
394 configureSurface(when, &resetNeeded);
395 }
396
397 if (changes && resetNeeded) {
398 // Send reset, unless this is the first time the device has been configured,
399 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +0000400 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
401 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 }
403}
404
405void TouchInputMapper::resolveExternalStylusPresence() {
406 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800407 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700408 mExternalStylusConnected = !devices.empty();
409
410 if (!mExternalStylusConnected) {
411 resetExternalStylus();
412 }
413}
414
415void TouchInputMapper::configureParameters() {
416 // Use the pointer presentation mode for devices that do not support distinct
417 // multitouch. The spot-based presentation relies on being able to accurately
418 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100420 ? Parameters::GestureMode::SINGLE_TOUCH
421 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422
423 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800424 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
425 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100427 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100429 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700430 } else if (gestureModeString != "default") {
431 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
432 }
433 }
434
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800435 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100437 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800438 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800441 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
442 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 // The device is a cursor device with a touch pad attached.
444 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100445 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446 } else {
447 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100448 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449 }
450
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800451 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452
453 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
455 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100461 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100463 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700464 } else if (deviceTypeString != "default") {
465 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
466 }
467 }
468
Michael Wright227c5542020-07-02 18:30:52 +0100469 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800470 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
471 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472
473 mParameters.hasAssociatedDisplay = false;
474 mParameters.associatedDisplayIsExternal = false;
475 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100476 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
477 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700478 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100479 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800480 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800482 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
483 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
485 }
486 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800487 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488 mParameters.hasAssociatedDisplay = true;
489 }
490
491 // Initial downs on external touch devices should wake the device.
492 // Normally we don't do this for internal touch screens to prevent them from waking
493 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 mParameters.wake = getDeviceContext().isExternal();
495 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496}
497
498void TouchInputMapper::dumpParameters(std::string& dump) {
499 dump += INDENT3 "Parameters:\n";
500
Chris Yea03dd232020-09-08 19:21:09 -0700501 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502
Chris Yea03dd232020-09-08 19:21:09 -0700503 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700504
505 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
506 "displayId='%s'\n",
507 toString(mParameters.hasAssociatedDisplay),
508 toString(mParameters.associatedDisplayIsExternal),
509 mParameters.uniqueDisplayId.c_str());
510 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
511}
512
513void TouchInputMapper::configureRawPointerAxes() {
514 mRawPointerAxes.clear();
515}
516
517void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
518 dump += INDENT3 "Raw Touch Axes:\n";
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
531 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
532}
533
534bool TouchInputMapper::hasExternalStylus() const {
535 return mExternalStylusConnected;
536}
537
538/**
539 * Determine which DisplayViewport to use.
540 * 1. If display port is specified, return the matching viewport. If matching viewport not
541 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800542 * 2. Always use the suggested viewport from WindowManagerService for pointers.
543 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700544 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800545 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700546 */
547std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800548 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800549 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700550 if (displayPort) {
551 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800552 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700553 }
554
Michael Wright227c5542020-07-02 18:30:52 +0100555 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800556 std::optional<DisplayViewport> viewport =
557 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
558 if (viewport) {
559 return viewport;
560 } else {
561 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
562 mConfig.defaultPointerDisplayId);
563 }
564 }
565
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 // Check if uniqueDisplayId is specified in idc file.
567 if (!mParameters.uniqueDisplayId.empty()) {
568 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
569 }
570
571 ViewportType viewportTypeToUse;
572 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100573 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700574 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100575 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700576 }
577
578 std::optional<DisplayViewport> viewport =
579 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100580 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700581 ALOGW("Input device %s should be associated with external display, "
582 "fallback to internal one for the external viewport is not found.",
583 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100584 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700585 }
586
587 return viewport;
588 }
589
590 // No associated display, return a non-display viewport.
591 DisplayViewport newViewport;
592 // Raw width and height in the natural orientation.
593 int32_t rawWidth = mRawPointerAxes.getRawWidth();
594 int32_t rawHeight = mRawPointerAxes.getRawHeight();
595 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
596 return std::make_optional(newViewport);
597}
598
599void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100600 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700601
602 resolveExternalStylusPresence();
603
604 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100605 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhanf192a102021-08-06 14:01:18 +0000606 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700607 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100608 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700609 if (hasStylus()) {
610 mSource |= AINPUT_SOURCE_STYLUS;
611 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800612 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700613 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100614 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700615 if (hasStylus()) {
616 mSource |= AINPUT_SOURCE_STYLUS;
617 }
618 if (hasExternalStylus()) {
619 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
620 }
Michael Wright227c5542020-07-02 18:30:52 +0100621 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700622 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100623 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700624 } else {
625 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100626 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700627 }
628
629 // Ensure we have valid X and Y axes.
630 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
631 ALOGW("Touch device '%s' did not report support for X or Y axis! "
632 "The device will be inoperable.",
633 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100634 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700635 return;
636 }
637
638 // Get associated display dimensions.
639 std::optional<DisplayViewport> newViewport = findViewport();
640 if (!newViewport) {
641 ALOGI("Touch device '%s' could not query the properties of its associated "
642 "display. The device will be inoperable until the display size "
643 "becomes available.",
644 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100645 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700646 return;
647 }
648
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000649 if (!newViewport->isActive) {
650 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
651 getDeviceName().c_str(), getDeviceId());
652 mDeviceMode = DeviceMode::DISABLED;
653 return;
654 }
655
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700656 // Raw width and height in the natural orientation.
657 int32_t rawWidth = mRawPointerAxes.getRawWidth();
658 int32_t rawHeight = mRawPointerAxes.getRawHeight();
659
660 bool viewportChanged = mViewport != *newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700661 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700662 if (viewportChanged) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700663 bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700664 mViewport = *newViewport;
665
Michael Wright227c5542020-07-02 18:30:52 +0100666 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700667 // Convert rotated viewport to natural surface coordinates.
668 int32_t naturalLogicalWidth, naturalLogicalHeight;
669 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
670 int32_t naturalPhysicalLeft, naturalPhysicalTop;
671 int32_t naturalDeviceWidth, naturalDeviceHeight;
672 switch (mViewport.orientation) {
673 case DISPLAY_ORIENTATION_90:
674 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
675 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
676 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
677 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800678 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700679 naturalPhysicalTop = mViewport.physicalLeft;
680 naturalDeviceWidth = mViewport.deviceHeight;
681 naturalDeviceHeight = mViewport.deviceWidth;
682 break;
683 case DISPLAY_ORIENTATION_180:
684 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
685 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
686 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
687 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
688 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
689 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
690 naturalDeviceWidth = mViewport.deviceWidth;
691 naturalDeviceHeight = mViewport.deviceHeight;
692 break;
693 case DISPLAY_ORIENTATION_270:
694 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
695 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
696 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
697 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
698 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800699 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700700 naturalDeviceWidth = mViewport.deviceHeight;
701 naturalDeviceHeight = mViewport.deviceWidth;
702 break;
703 case DISPLAY_ORIENTATION_0:
704 default:
705 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
706 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
707 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
708 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
709 naturalPhysicalLeft = mViewport.physicalLeft;
710 naturalPhysicalTop = mViewport.physicalTop;
711 naturalDeviceWidth = mViewport.deviceWidth;
712 naturalDeviceHeight = mViewport.deviceHeight;
713 break;
714 }
715
716 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
717 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
718 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
719 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
720 }
721
722 mPhysicalWidth = naturalPhysicalWidth;
723 mPhysicalHeight = naturalPhysicalHeight;
724 mPhysicalLeft = naturalPhysicalLeft;
725 mPhysicalTop = naturalPhysicalTop;
726
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700727 const int32_t oldSurfaceWidth = mRawSurfaceWidth;
728 const int32_t oldSurfaceHeight = mRawSurfaceHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800729 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
730 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700731 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
732 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800733 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
734 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700735
Prabir Pradhand7482e72021-03-09 13:54:55 -0800736 if (isPerWindowInputRotationEnabled()) {
737 // When per-window input rotation is enabled, InputReader works in the un-rotated
738 // coordinate space, so we don't need to do anything if the device is already
739 // orientation-aware. If the device is not orientation-aware, then we need to apply
740 // the inverse rotation of the display so that when the display rotation is applied
741 // later as a part of the per-window transform, we get the expected screen
742 // coordinates.
743 mSurfaceOrientation = mParameters.orientationAware
744 ? DISPLAY_ORIENTATION_0
745 : getInverseRotation(mViewport.orientation);
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700746 // For orientation-aware devices that work in the un-rotated coordinate space, the
747 // viewport update should be skipped if it is only a change in the orientation.
748 skipViewportUpdate = mParameters.orientationAware &&
749 mRawSurfaceWidth == oldSurfaceWidth &&
750 mRawSurfaceHeight == oldSurfaceHeight && viewportOrientationChanged;
Prabir Pradhand7482e72021-03-09 13:54:55 -0800751 } else {
752 mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation
753 : DISPLAY_ORIENTATION_0;
754 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700755 } else {
756 mPhysicalWidth = rawWidth;
757 mPhysicalHeight = rawHeight;
758 mPhysicalLeft = 0;
759 mPhysicalTop = 0;
760
Arthur Hung4197f6b2020-03-16 15:39:59 +0800761 mRawSurfaceWidth = rawWidth;
762 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700763 mSurfaceLeft = 0;
764 mSurfaceTop = 0;
765 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
766 }
767 }
768
769 // If moving between pointer modes, need to reset some state.
770 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
771 if (deviceModeChanged) {
772 mOrientedRanges.clear();
773 }
774
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800775 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
776 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100777 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800778 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhanf192a102021-08-06 14:01:18 +0000779 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
780 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800781 if (mPointerController == nullptr) {
782 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700783 }
Prabir Pradhanf192a102021-08-06 14:01:18 +0000784 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800785 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
786 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700787 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100788 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700789 }
790
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700791 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700792 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
793 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800794 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700795 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
796
797 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800798 mXScale = float(mRawSurfaceWidth) / rawWidth;
799 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700800 mXTranslate = -mSurfaceLeft;
801 mYTranslate = -mSurfaceTop;
802 mXPrecision = 1.0f / mXScale;
803 mYPrecision = 1.0f / mYScale;
804
805 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
806 mOrientedRanges.x.source = mSource;
807 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
808 mOrientedRanges.y.source = mSource;
809
810 configureVirtualKeys();
811
812 // Scale factor for terms that are not oriented in a particular axis.
813 // If the pixels are square then xScale == yScale otherwise we fake it
814 // by choosing an average.
815 mGeometricScale = avg(mXScale, mYScale);
816
817 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800818 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700819
820 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100821 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700822 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
823 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
824 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
825 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
826 } else {
827 mSizeScale = 0.0f;
828 }
829
830 mOrientedRanges.haveTouchSize = true;
831 mOrientedRanges.haveToolSize = true;
832 mOrientedRanges.haveSize = true;
833
834 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
835 mOrientedRanges.touchMajor.source = mSource;
836 mOrientedRanges.touchMajor.min = 0;
837 mOrientedRanges.touchMajor.max = diagonalSize;
838 mOrientedRanges.touchMajor.flat = 0;
839 mOrientedRanges.touchMajor.fuzz = 0;
840 mOrientedRanges.touchMajor.resolution = 0;
841
842 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
843 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
844
845 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
846 mOrientedRanges.toolMajor.source = mSource;
847 mOrientedRanges.toolMajor.min = 0;
848 mOrientedRanges.toolMajor.max = diagonalSize;
849 mOrientedRanges.toolMajor.flat = 0;
850 mOrientedRanges.toolMajor.fuzz = 0;
851 mOrientedRanges.toolMajor.resolution = 0;
852
853 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
854 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
855
856 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
857 mOrientedRanges.size.source = mSource;
858 mOrientedRanges.size.min = 0;
859 mOrientedRanges.size.max = 1.0;
860 mOrientedRanges.size.flat = 0;
861 mOrientedRanges.size.fuzz = 0;
862 mOrientedRanges.size.resolution = 0;
863 } else {
864 mSizeScale = 0.0f;
865 }
866
867 // Pressure factors.
868 mPressureScale = 0;
869 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100870 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
871 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700872 if (mCalibration.havePressureScale) {
873 mPressureScale = mCalibration.pressureScale;
874 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
875 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
876 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
877 }
878 }
879
880 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
881 mOrientedRanges.pressure.source = mSource;
882 mOrientedRanges.pressure.min = 0;
883 mOrientedRanges.pressure.max = pressureMax;
884 mOrientedRanges.pressure.flat = 0;
885 mOrientedRanges.pressure.fuzz = 0;
886 mOrientedRanges.pressure.resolution = 0;
887
888 // Tilt
889 mTiltXCenter = 0;
890 mTiltXScale = 0;
891 mTiltYCenter = 0;
892 mTiltYScale = 0;
893 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
894 if (mHaveTilt) {
895 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
896 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
897 mTiltXScale = M_PI / 180;
898 mTiltYScale = M_PI / 180;
899
900 mOrientedRanges.haveTilt = true;
901
902 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
903 mOrientedRanges.tilt.source = mSource;
904 mOrientedRanges.tilt.min = 0;
905 mOrientedRanges.tilt.max = M_PI_2;
906 mOrientedRanges.tilt.flat = 0;
907 mOrientedRanges.tilt.fuzz = 0;
908 mOrientedRanges.tilt.resolution = 0;
909 }
910
911 // Orientation
912 mOrientationScale = 0;
913 if (mHaveTilt) {
914 mOrientedRanges.haveOrientation = true;
915
916 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
917 mOrientedRanges.orientation.source = mSource;
918 mOrientedRanges.orientation.min = -M_PI;
919 mOrientedRanges.orientation.max = M_PI;
920 mOrientedRanges.orientation.flat = 0;
921 mOrientedRanges.orientation.fuzz = 0;
922 mOrientedRanges.orientation.resolution = 0;
923 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100924 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100926 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700927 if (mRawPointerAxes.orientation.valid) {
928 if (mRawPointerAxes.orientation.maxValue > 0) {
929 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
930 } else if (mRawPointerAxes.orientation.minValue < 0) {
931 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
932 } else {
933 mOrientationScale = 0;
934 }
935 }
936 }
937
938 mOrientedRanges.haveOrientation = true;
939
940 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
941 mOrientedRanges.orientation.source = mSource;
942 mOrientedRanges.orientation.min = -M_PI_2;
943 mOrientedRanges.orientation.max = M_PI_2;
944 mOrientedRanges.orientation.flat = 0;
945 mOrientedRanges.orientation.fuzz = 0;
946 mOrientedRanges.orientation.resolution = 0;
947 }
948
949 // Distance
950 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100951 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
952 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700953 if (mCalibration.haveDistanceScale) {
954 mDistanceScale = mCalibration.distanceScale;
955 } else {
956 mDistanceScale = 1.0f;
957 }
958 }
959
960 mOrientedRanges.haveDistance = true;
961
962 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
963 mOrientedRanges.distance.source = mSource;
964 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
965 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
966 mOrientedRanges.distance.flat = 0;
967 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
968 mOrientedRanges.distance.resolution = 0;
969 }
970
971 // Compute oriented precision, scales and ranges.
972 // Note that the maximum value reported is an inclusive maximum value so it is one
973 // unit less than the total width or height of surface.
974 switch (mSurfaceOrientation) {
975 case DISPLAY_ORIENTATION_90:
976 case DISPLAY_ORIENTATION_270:
977 mOrientedXPrecision = mYPrecision;
978 mOrientedYPrecision = mXPrecision;
979
980 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800981 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700982 mOrientedRanges.x.flat = 0;
983 mOrientedRanges.x.fuzz = 0;
984 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
985
986 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800987 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700988 mOrientedRanges.y.flat = 0;
989 mOrientedRanges.y.fuzz = 0;
990 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
991 break;
992
993 default:
994 mOrientedXPrecision = mXPrecision;
995 mOrientedYPrecision = mYPrecision;
996
997 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800998 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700999 mOrientedRanges.x.flat = 0;
1000 mOrientedRanges.x.fuzz = 0;
1001 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1002
1003 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001004 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001005 mOrientedRanges.y.flat = 0;
1006 mOrientedRanges.y.fuzz = 0;
1007 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1008 break;
1009 }
1010
1011 // Location
1012 updateAffineTransformation();
1013
Michael Wright227c5542020-07-02 18:30:52 +01001014 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001015 // Compute pointer gesture detection parameters.
1016 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001017 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001018
1019 // Scale movements such that one whole swipe of the touch pad covers a
1020 // given area relative to the diagonal size of the display when no acceleration
1021 // is applied.
1022 // Assume that the touch pad has a square aspect ratio such that movements in
1023 // X and Y of the same number of raw units cover the same physical distance.
1024 mPointerXMovementScale =
1025 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1026 mPointerYMovementScale = mPointerXMovementScale;
1027
1028 // Scale zooms to cover a smaller range of the display than movements do.
1029 // This value determines the area around the pointer that is affected by freeform
1030 // pointer gestures.
1031 mPointerXZoomScale =
1032 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1033 mPointerYZoomScale = mPointerXZoomScale;
1034
1035 // Max width between pointers to detect a swipe gesture is more than some fraction
1036 // of the diagonal axis of the touch pad. Touches that are wider than this are
1037 // translated into freeform gestures.
1038 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1039
1040 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001041 const nsecs_t readTime = when; // synthetic event
1042 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001043 }
1044
1045 // Inform the dispatcher about the changes.
1046 *outResetNeeded = true;
1047 bumpGeneration();
1048 }
1049}
1050
1051void TouchInputMapper::dumpSurface(std::string& dump) {
1052 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001053 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1054 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001055 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1056 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001057 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1058 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1060 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1061 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1062 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1063 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1064}
1065
1066void TouchInputMapper::configureVirtualKeys() {
1067 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001068 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001069
1070 mVirtualKeys.clear();
1071
1072 if (virtualKeyDefinitions.size() == 0) {
1073 return;
1074 }
1075
1076 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1077 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1078 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1079 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1080
1081 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1082 VirtualKey virtualKey;
1083
1084 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1085 int32_t keyCode;
1086 int32_t dummyKeyMetaState;
1087 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001088 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1089 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001090 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1091 continue; // drop the key
1092 }
1093
1094 virtualKey.keyCode = keyCode;
1095 virtualKey.flags = flags;
1096
1097 // convert the key definition's display coordinates into touch coordinates for a hit box
1098 int32_t halfWidth = virtualKeyDefinition.width / 2;
1099 int32_t halfHeight = virtualKeyDefinition.height / 2;
1100
1101 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001102 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001103 touchScreenLeft;
1104 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001105 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001106 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001107 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1108 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001110 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1111 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112 touchScreenTop;
1113 mVirtualKeys.push_back(virtualKey);
1114 }
1115}
1116
1117void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1118 if (!mVirtualKeys.empty()) {
1119 dump += INDENT3 "Virtual Keys:\n";
1120
1121 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1122 const VirtualKey& virtualKey = mVirtualKeys[i];
1123 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1124 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1125 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1126 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1127 }
1128 }
1129}
1130
1131void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001132 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 Calibration& out = mCalibration;
1134
1135 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 String8 sizeCalibrationString;
1138 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1139 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001148 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 } else if (sizeCalibrationString != "default") {
1150 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1151 }
1152 }
1153
1154 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1155 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1156 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1157
1158 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001159 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 String8 pressureCalibrationString;
1161 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1162 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001164 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001165 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (pressureCalibrationString != "default") {
1169 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1170 pressureCalibrationString.string());
1171 }
1172 }
1173
1174 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1175
1176 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 String8 orientationCalibrationString;
1179 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1180 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 } else if (orientationCalibrationString != "default") {
1187 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1188 orientationCalibrationString.string());
1189 }
1190 }
1191
1192 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001193 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001194 String8 distanceCalibrationString;
1195 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1196 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (distanceCalibrationString != "default") {
1201 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1202 distanceCalibrationString.string());
1203 }
1204 }
1205
1206 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1207
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 String8 coverageCalibrationString;
1210 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1211 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001214 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 } else if (coverageCalibrationString != "default") {
1216 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1217 coverageCalibrationString.string());
1218 }
1219 }
1220}
1221
1222void TouchInputMapper::resolveCalibration() {
1223 // Size
1224 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001225 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1226 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 }
1228 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001229 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 }
1231
1232 // Pressure
1233 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001234 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1235 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 }
1237 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001238 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 }
1240
1241 // Orientation
1242 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001243 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1244 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 }
1246 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001247 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249
1250 // Distance
1251 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001252 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1253 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 }
1255 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001256 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258
1259 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001260 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1261 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263}
1264
1265void TouchInputMapper::dumpCalibration(std::string& dump) {
1266 dump += INDENT3 "Calibration:\n";
1267
1268 // Size
1269 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001270 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 dump += INDENT4 "touch.size.calibration: none\n";
1272 break;
Michael Wright227c5542020-07-02 18:30:52 +01001273 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274 dump += INDENT4 "touch.size.calibration: geometric\n";
1275 break;
Michael Wright227c5542020-07-02 18:30:52 +01001276 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 dump += INDENT4 "touch.size.calibration: diameter\n";
1278 break;
Michael Wright227c5542020-07-02 18:30:52 +01001279 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 dump += INDENT4 "touch.size.calibration: box\n";
1281 break;
Michael Wright227c5542020-07-02 18:30:52 +01001282 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 dump += INDENT4 "touch.size.calibration: area\n";
1284 break;
1285 default:
1286 ALOG_ASSERT(false);
1287 }
1288
1289 if (mCalibration.haveSizeScale) {
1290 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1291 }
1292
1293 if (mCalibration.haveSizeBias) {
1294 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1295 }
1296
1297 if (mCalibration.haveSizeIsSummed) {
1298 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1299 toString(mCalibration.sizeIsSummed));
1300 }
1301
1302 // Pressure
1303 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001304 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 dump += INDENT4 "touch.pressure.calibration: none\n";
1306 break;
Michael Wright227c5542020-07-02 18:30:52 +01001307 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 dump += INDENT4 "touch.pressure.calibration: physical\n";
1309 break;
Michael Wright227c5542020-07-02 18:30:52 +01001310 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1312 break;
1313 default:
1314 ALOG_ASSERT(false);
1315 }
1316
1317 if (mCalibration.havePressureScale) {
1318 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1319 }
1320
1321 // Orientation
1322 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001323 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 dump += INDENT4 "touch.orientation.calibration: none\n";
1325 break;
Michael Wright227c5542020-07-02 18:30:52 +01001326 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001327 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1328 break;
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.orientation.calibration: vector\n";
1331 break;
1332 default:
1333 ALOG_ASSERT(false);
1334 }
1335
1336 // Distance
1337 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001338 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001339 dump += INDENT4 "touch.distance.calibration: none\n";
1340 break;
Michael Wright227c5542020-07-02 18:30:52 +01001341 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001342 dump += INDENT4 "touch.distance.calibration: scaled\n";
1343 break;
1344 default:
1345 ALOG_ASSERT(false);
1346 }
1347
1348 if (mCalibration.haveDistanceScale) {
1349 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1350 }
1351
1352 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001353 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001354 dump += INDENT4 "touch.coverage.calibration: none\n";
1355 break;
Michael Wright227c5542020-07-02 18:30:52 +01001356 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 dump += INDENT4 "touch.coverage.calibration: box\n";
1358 break;
1359 default:
1360 ALOG_ASSERT(false);
1361 }
1362}
1363
1364void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1365 dump += INDENT3 "Affine Transformation:\n";
1366
1367 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1368 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1369 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1370 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1371 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1372 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1373}
1374
1375void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001376 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001377 mSurfaceOrientation);
1378}
1379
1380void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001381 mCursorButtonAccumulator.reset(getDeviceContext());
1382 mCursorScrollAccumulator.reset(getDeviceContext());
1383 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001384
1385 mPointerVelocityControl.reset();
1386 mWheelXVelocityControl.reset();
1387 mWheelYVelocityControl.reset();
1388
1389 mRawStatesPending.clear();
1390 mCurrentRawState.clear();
1391 mCurrentCookedState.clear();
1392 mLastRawState.clear();
1393 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001394 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001395 mSentHoverEnter = false;
1396 mHavePointerIds = false;
1397 mCurrentMotionAborted = false;
1398 mDownTime = 0;
1399
1400 mCurrentVirtualKey.down = false;
1401
1402 mPointerGesture.reset();
1403 mPointerSimple.reset();
1404 resetExternalStylus();
1405
1406 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001407 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001408 mPointerController->clearSpots();
1409 }
1410
1411 InputMapper::reset(when);
1412}
1413
1414void TouchInputMapper::resetExternalStylus() {
1415 mExternalStylusState.clear();
1416 mExternalStylusId = -1;
1417 mExternalStylusFusionTimeout = LLONG_MAX;
1418 mExternalStylusDataPending = false;
1419}
1420
1421void TouchInputMapper::clearStylusDataPendingFlags() {
1422 mExternalStylusDataPending = false;
1423 mExternalStylusFusionTimeout = LLONG_MAX;
1424}
1425
1426void TouchInputMapper::process(const RawEvent* rawEvent) {
1427 mCursorButtonAccumulator.process(rawEvent);
1428 mCursorScrollAccumulator.process(rawEvent);
1429 mTouchButtonAccumulator.process(rawEvent);
1430
1431 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001432 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001433 }
1434}
1435
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001436void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001437 // Push a new state.
1438 mRawStatesPending.emplace_back();
1439
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001440 RawState& next = mRawStatesPending.back();
1441 next.clear();
1442 next.when = when;
1443 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444
1445 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001446 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1448
1449 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001450 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1451 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001452 mCursorScrollAccumulator.finishSync();
1453
1454 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001455 syncTouch(when, &next);
1456
1457 // The last RawState is the actually second to last, since we just added a new state
1458 const RawState& last =
1459 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001460
1461 // Assign pointer ids.
1462 if (!mHavePointerIds) {
1463 assignPointerIds(last, next);
1464 }
1465
1466#if DEBUG_RAW_EVENTS
1467 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001468 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001469 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1470 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1471 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1472 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001473#endif
1474
Arthur Hung9ad18942021-06-19 02:04:46 +00001475 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1476 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1477 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1478 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1479 next.rawPointerData.hoveringIdBits.value);
1480 }
1481
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001482 processRawTouches(false /*timeout*/);
1483}
1484
1485void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001486 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001487 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001488 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001489 mCurrentCookedState.clear();
1490 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001491 return;
1492 }
1493
1494 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1495 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1496 // touching the current state will only observe the events that have been dispatched to the
1497 // rest of the pipeline.
1498 const size_t N = mRawStatesPending.size();
1499 size_t count;
1500 for (count = 0; count < N; count++) {
1501 const RawState& next = mRawStatesPending[count];
1502
1503 // A failure to assign the stylus id means that we're waiting on stylus data
1504 // and so should defer the rest of the pipeline.
1505 if (assignExternalStylusId(next, timeout)) {
1506 break;
1507 }
1508
1509 // All ready to go.
1510 clearStylusDataPendingFlags();
1511 mCurrentRawState.copyFrom(next);
1512 if (mCurrentRawState.when < mLastRawState.when) {
1513 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001514 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001515 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001516 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 }
1518 if (count != 0) {
1519 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1520 }
1521
1522 if (mExternalStylusDataPending) {
1523 if (timeout) {
1524 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1525 clearStylusDataPendingFlags();
1526 mCurrentRawState.copyFrom(mLastRawState);
1527#if DEBUG_STYLUS_FUSION
1528 ALOGD("Timeout expired, synthesizing event with new stylus data");
1529#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001530 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1531 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001532 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1533 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1534 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1535 }
1536 }
1537}
1538
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001539void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001540 // Always start with a clean state.
1541 mCurrentCookedState.clear();
1542
1543 // Apply stylus buttons to current raw state.
1544 applyExternalStylusButtonState(when);
1545
1546 // Handle policy on initial down or hover events.
1547 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1548 mCurrentRawState.rawPointerData.pointerCount != 0;
1549
1550 uint32_t policyFlags = 0;
1551 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1552 if (initialDown || buttonsPressed) {
1553 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001554 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001555 getContext()->fadePointer();
1556 }
1557
1558 if (mParameters.wake) {
1559 policyFlags |= POLICY_FLAG_WAKE;
1560 }
1561 }
1562
1563 // Consume raw off-screen touches before cooking pointer data.
1564 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001565 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001566 mCurrentRawState.rawPointerData.clear();
1567 }
1568
1569 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1570 // with cooked pointer data that has the same ids and indices as the raw data.
1571 // The following code can use either the raw or cooked data, as needed.
1572 cookPointerData();
1573
1574 // Apply stylus pressure to current cooked state.
1575 applyExternalStylusTouchState(when);
1576
1577 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001578 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1579 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001580 mCurrentCookedState.buttonState);
1581
1582 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001583 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001584 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1585 uint32_t id = idBits.clearFirstMarkedBit();
1586 const RawPointerData::Pointer& pointer =
1587 mCurrentRawState.rawPointerData.pointerForId(id);
1588 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1589 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1590 mCurrentCookedState.stylusIdBits.markBit(id);
1591 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1592 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1593 mCurrentCookedState.fingerIdBits.markBit(id);
1594 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1595 mCurrentCookedState.mouseIdBits.markBit(id);
1596 }
1597 }
1598 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1599 uint32_t id = idBits.clearFirstMarkedBit();
1600 const RawPointerData::Pointer& pointer =
1601 mCurrentRawState.rawPointerData.pointerForId(id);
1602 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1603 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1604 mCurrentCookedState.stylusIdBits.markBit(id);
1605 }
1606 }
1607
1608 // Stylus takes precedence over all tools, then mouse, then finger.
1609 PointerUsage pointerUsage = mPointerUsage;
1610 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1611 mCurrentCookedState.mouseIdBits.clear();
1612 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001613 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001614 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1615 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001616 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1618 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001619 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620 }
1621
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001622 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001623 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001624 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625
1626 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001627 dispatchButtonRelease(when, readTime, policyFlags);
1628 dispatchHoverExit(when, readTime, policyFlags);
1629 dispatchTouches(when, readTime, policyFlags);
1630 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1631 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 }
1633
1634 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1635 mCurrentMotionAborted = false;
1636 }
1637 }
1638
1639 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001640 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001641 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1642 mCurrentCookedState.buttonState);
1643
1644 // Clear some transient state.
1645 mCurrentRawState.rawVScroll = 0;
1646 mCurrentRawState.rawHScroll = 0;
1647
1648 // Copy current touch to last touch in preparation for the next cycle.
1649 mLastRawState.copyFrom(mCurrentRawState);
1650 mLastCookedState.copyFrom(mCurrentCookedState);
1651}
1652
Garfield Tanc734e4f2021-01-15 20:01:39 -08001653void TouchInputMapper::updateTouchSpots() {
1654 if (!mConfig.showTouches || mPointerController == nullptr) {
1655 return;
1656 }
1657
1658 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1659 // clear touch spots.
1660 if (mDeviceMode != DeviceMode::DIRECT &&
1661 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1662 return;
1663 }
1664
1665 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1666 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1667
1668 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001669 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1670 mCurrentCookedState.cookedPointerData.idToIndex,
1671 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001672}
1673
1674bool TouchInputMapper::isTouchScreen() {
1675 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1676 mParameters.hasAssociatedDisplay;
1677}
1678
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001679void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001680 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001681 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1682 }
1683}
1684
1685void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1686 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1687 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1688
1689 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1690 float pressure = mExternalStylusState.pressure;
1691 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1692 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1693 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1694 }
1695 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1696 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1697
1698 PointerProperties& properties =
1699 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1700 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1701 properties.toolType = mExternalStylusState.toolType;
1702 }
1703 }
1704}
1705
1706bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001707 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001708 return false;
1709 }
1710
1711 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1712 state.rawPointerData.pointerCount != 0;
1713 if (initialDown) {
1714 if (mExternalStylusState.pressure != 0.0f) {
1715#if DEBUG_STYLUS_FUSION
1716 ALOGD("Have both stylus and touch data, beginning fusion");
1717#endif
1718 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1719 } else if (timeout) {
1720#if DEBUG_STYLUS_FUSION
1721 ALOGD("Timeout expired, assuming touch is not a stylus.");
1722#endif
1723 resetExternalStylus();
1724 } else {
1725 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1726 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1727 }
1728#if DEBUG_STYLUS_FUSION
1729 ALOGD("No stylus data but stylus is connected, requesting timeout "
1730 "(%" PRId64 "ms)",
1731 mExternalStylusFusionTimeout);
1732#endif
1733 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1734 return true;
1735 }
1736 }
1737
1738 // Check if the stylus pointer has gone up.
1739 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1740#if DEBUG_STYLUS_FUSION
1741 ALOGD("Stylus pointer is going up");
1742#endif
1743 mExternalStylusId = -1;
1744 }
1745
1746 return false;
1747}
1748
1749void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001750 if (mDeviceMode == DeviceMode::POINTER) {
1751 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001752 // Since this is a synthetic event, we can consider its latency to be zero
1753 const nsecs_t readTime = when;
1754 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001755 }
Michael Wright227c5542020-07-02 18:30:52 +01001756 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001757 if (mExternalStylusFusionTimeout < when) {
1758 processRawTouches(true /*timeout*/);
1759 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1760 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1761 }
1762 }
1763}
1764
1765void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1766 mExternalStylusState.copyFrom(state);
1767 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1768 // We're either in the middle of a fused stream of data or we're waiting on data before
1769 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1770 // data.
1771 mExternalStylusDataPending = true;
1772 processRawTouches(false /*timeout*/);
1773 }
1774}
1775
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001776bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001777 // Check for release of a virtual key.
1778 if (mCurrentVirtualKey.down) {
1779 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1780 // Pointer went up while virtual key was down.
1781 mCurrentVirtualKey.down = false;
1782 if (!mCurrentVirtualKey.ignored) {
1783#if DEBUG_VIRTUAL_KEYS
1784 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1785 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1786#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001787 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001788 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1789 }
1790 return true;
1791 }
1792
1793 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1794 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1795 const RawPointerData::Pointer& pointer =
1796 mCurrentRawState.rawPointerData.pointerForId(id);
1797 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1798 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1799 // Pointer is still within the space of the virtual key.
1800 return true;
1801 }
1802 }
1803
1804 // Pointer left virtual key area or another pointer also went down.
1805 // Send key cancellation but do not consume the touch yet.
1806 // This is useful when the user swipes through from the virtual key area
1807 // into the main display surface.
1808 mCurrentVirtualKey.down = false;
1809 if (!mCurrentVirtualKey.ignored) {
1810#if DEBUG_VIRTUAL_KEYS
1811 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1812 mCurrentVirtualKey.scanCode);
1813#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001814 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001815 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1816 AKEY_EVENT_FLAG_CANCELED);
1817 }
1818 }
1819
1820 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1821 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1822 // Pointer just went down. Check for virtual key press or off-screen touches.
1823 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1824 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001825 // Exclude unscaled device for inside surface checking.
1826 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001827 // If exactly one pointer went down, check for virtual key hit.
1828 // Otherwise we will drop the entire stroke.
1829 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1830 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1831 if (virtualKey) {
1832 mCurrentVirtualKey.down = true;
1833 mCurrentVirtualKey.downTime = when;
1834 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1835 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1836 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001837 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1838 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001839
1840 if (!mCurrentVirtualKey.ignored) {
1841#if DEBUG_VIRTUAL_KEYS
1842 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1843 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1844#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001845 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846 AKEY_EVENT_FLAG_FROM_SYSTEM |
1847 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1848 }
1849 }
1850 }
1851 return true;
1852 }
1853 }
1854
1855 // Disable all virtual key touches that happen within a short time interval of the
1856 // most recent touch within the screen area. The idea is to filter out stray
1857 // virtual key presses when interacting with the touch screen.
1858 //
1859 // Problems we're trying to solve:
1860 //
1861 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1862 // virtual key area that is implemented by a separate touch panel and accidentally
1863 // triggers a virtual key.
1864 //
1865 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1866 // area and accidentally triggers a virtual key. This often happens when virtual keys
1867 // are layed out below the screen near to where the on screen keyboard's space bar
1868 // is displayed.
1869 if (mConfig.virtualKeyQuietTime > 0 &&
1870 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001871 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001872 }
1873 return false;
1874}
1875
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001876void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001877 int32_t keyEventAction, int32_t keyEventFlags) {
1878 int32_t keyCode = mCurrentVirtualKey.keyCode;
1879 int32_t scanCode = mCurrentVirtualKey.scanCode;
1880 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001881 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001882 policyFlags |= POLICY_FLAG_VIRTUAL;
1883
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001884 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1885 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1886 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001887 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001888}
1889
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001890void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001891 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1892 if (!currentIdBits.isEmpty()) {
1893 int32_t metaState = getContext()->getGlobalMetaState();
1894 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001895 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1896 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001897 mCurrentCookedState.cookedPointerData.pointerProperties,
1898 mCurrentCookedState.cookedPointerData.pointerCoords,
1899 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1900 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1901 mCurrentMotionAborted = true;
1902 }
1903}
1904
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001905void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001906 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1907 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1908 int32_t metaState = getContext()->getGlobalMetaState();
1909 int32_t buttonState = mCurrentCookedState.buttonState;
1910
1911 if (currentIdBits == lastIdBits) {
1912 if (!currentIdBits.isEmpty()) {
1913 // No pointer id changes so this is a move event.
1914 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001915 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1916 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001917 mCurrentCookedState.cookedPointerData.pointerProperties,
1918 mCurrentCookedState.cookedPointerData.pointerCoords,
1919 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1920 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1921 }
1922 } else {
1923 // There may be pointers going up and pointers going down and pointers moving
1924 // all at the same time.
1925 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1926 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1927 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1928 BitSet32 dispatchedIdBits(lastIdBits.value);
1929
1930 // Update last coordinates of pointers that have moved so that we observe the new
1931 // pointer positions at the same time as other pointers that have just gone up.
1932 bool moveNeeded =
1933 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1934 mCurrentCookedState.cookedPointerData.pointerCoords,
1935 mCurrentCookedState.cookedPointerData.idToIndex,
1936 mLastCookedState.cookedPointerData.pointerProperties,
1937 mLastCookedState.cookedPointerData.pointerCoords,
1938 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1939 if (buttonState != mLastCookedState.buttonState) {
1940 moveNeeded = true;
1941 }
1942
1943 // Dispatch pointer up events.
1944 while (!upIdBits.isEmpty()) {
1945 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001946 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001947 if (isCanceled) {
1948 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1949 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001950 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001951 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001952 mLastCookedState.cookedPointerData.pointerProperties,
1953 mLastCookedState.cookedPointerData.pointerCoords,
1954 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1955 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1956 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001957 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001958 }
1959
1960 // Dispatch move events if any of the remaining pointers moved from their old locations.
1961 // Although applications receive new locations as part of individual pointer up
1962 // events, they do not generally handle them except when presented in a move event.
1963 if (moveNeeded && !moveIdBits.isEmpty()) {
1964 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001965 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1966 metaState, buttonState, 0,
1967 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001968 mCurrentCookedState.cookedPointerData.pointerCoords,
1969 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1970 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1971 }
1972
1973 // Dispatch pointer down events using the new pointer locations.
1974 while (!downIdBits.isEmpty()) {
1975 uint32_t downId = downIdBits.clearFirstMarkedBit();
1976 dispatchedIdBits.markBit(downId);
1977
1978 if (dispatchedIdBits.count() == 1) {
1979 // First pointer is going down. Set down time.
1980 mDownTime = when;
1981 }
1982
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001983 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
1984 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001985 mCurrentCookedState.cookedPointerData.pointerProperties,
1986 mCurrentCookedState.cookedPointerData.pointerCoords,
1987 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1988 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1989 }
1990 }
1991}
1992
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001993void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001994 if (mSentHoverEnter &&
1995 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1996 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1997 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001998 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
1999 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002000 mLastCookedState.cookedPointerData.pointerProperties,
2001 mLastCookedState.cookedPointerData.pointerCoords,
2002 mLastCookedState.cookedPointerData.idToIndex,
2003 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2004 mOrientedYPrecision, mDownTime);
2005 mSentHoverEnter = false;
2006 }
2007}
2008
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002009void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2010 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002011 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2012 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2013 int32_t metaState = getContext()->getGlobalMetaState();
2014 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002015 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2016 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002017 mCurrentCookedState.cookedPointerData.pointerProperties,
2018 mCurrentCookedState.cookedPointerData.pointerCoords,
2019 mCurrentCookedState.cookedPointerData.idToIndex,
2020 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2021 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2022 mSentHoverEnter = true;
2023 }
2024
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002025 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2026 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002027 mCurrentCookedState.cookedPointerData.pointerProperties,
2028 mCurrentCookedState.cookedPointerData.pointerCoords,
2029 mCurrentCookedState.cookedPointerData.idToIndex,
2030 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2031 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2032 }
2033}
2034
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002035void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002036 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2037 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2038 const int32_t metaState = getContext()->getGlobalMetaState();
2039 int32_t buttonState = mLastCookedState.buttonState;
2040 while (!releasedButtons.isEmpty()) {
2041 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2042 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002043 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002044 actionButton, 0, metaState, buttonState, 0,
2045 mCurrentCookedState.cookedPointerData.pointerProperties,
2046 mCurrentCookedState.cookedPointerData.pointerCoords,
2047 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2048 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2049 }
2050}
2051
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002052void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002053 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2054 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2055 const int32_t metaState = getContext()->getGlobalMetaState();
2056 int32_t buttonState = mLastCookedState.buttonState;
2057 while (!pressedButtons.isEmpty()) {
2058 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2059 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002060 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2061 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002062 mCurrentCookedState.cookedPointerData.pointerProperties,
2063 mCurrentCookedState.cookedPointerData.pointerCoords,
2064 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2065 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2066 }
2067}
2068
2069const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2070 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2071 return cookedPointerData.touchingIdBits;
2072 }
2073 return cookedPointerData.hoveringIdBits;
2074}
2075
2076void TouchInputMapper::cookPointerData() {
2077 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2078
2079 mCurrentCookedState.cookedPointerData.clear();
2080 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2081 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2082 mCurrentRawState.rawPointerData.hoveringIdBits;
2083 mCurrentCookedState.cookedPointerData.touchingIdBits =
2084 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002085 mCurrentCookedState.cookedPointerData.canceledIdBits =
2086 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002087
2088 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2089 mCurrentCookedState.buttonState = 0;
2090 } else {
2091 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2092 }
2093
2094 // Walk through the the active pointers and map device coordinates onto
2095 // surface coordinates and adjust for display orientation.
2096 for (uint32_t i = 0; i < currentPointerCount; i++) {
2097 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2098
2099 // Size
2100 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2101 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002102 case Calibration::SizeCalibration::GEOMETRIC:
2103 case Calibration::SizeCalibration::DIAMETER:
2104 case Calibration::SizeCalibration::BOX:
2105 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002106 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2107 touchMajor = in.touchMajor;
2108 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2109 toolMajor = in.toolMajor;
2110 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2111 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2112 : in.touchMajor;
2113 } else if (mRawPointerAxes.touchMajor.valid) {
2114 toolMajor = touchMajor = in.touchMajor;
2115 toolMinor = touchMinor =
2116 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2117 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2118 : in.touchMajor;
2119 } else if (mRawPointerAxes.toolMajor.valid) {
2120 touchMajor = toolMajor = in.toolMajor;
2121 touchMinor = toolMinor =
2122 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2123 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2124 : in.toolMajor;
2125 } else {
2126 ALOG_ASSERT(false,
2127 "No touch or tool axes. "
2128 "Size calibration should have been resolved to NONE.");
2129 touchMajor = 0;
2130 touchMinor = 0;
2131 toolMajor = 0;
2132 toolMinor = 0;
2133 size = 0;
2134 }
2135
2136 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2137 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2138 if (touchingCount > 1) {
2139 touchMajor /= touchingCount;
2140 touchMinor /= touchingCount;
2141 toolMajor /= touchingCount;
2142 toolMinor /= touchingCount;
2143 size /= touchingCount;
2144 }
2145 }
2146
Michael Wright227c5542020-07-02 18:30:52 +01002147 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002148 touchMajor *= mGeometricScale;
2149 touchMinor *= mGeometricScale;
2150 toolMajor *= mGeometricScale;
2151 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002152 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002153 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2154 touchMinor = touchMajor;
2155 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2156 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002157 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002158 touchMinor = touchMajor;
2159 toolMinor = toolMajor;
2160 }
2161
2162 mCalibration.applySizeScaleAndBias(&touchMajor);
2163 mCalibration.applySizeScaleAndBias(&touchMinor);
2164 mCalibration.applySizeScaleAndBias(&toolMajor);
2165 mCalibration.applySizeScaleAndBias(&toolMinor);
2166 size *= mSizeScale;
2167 break;
2168 default:
2169 touchMajor = 0;
2170 touchMinor = 0;
2171 toolMajor = 0;
2172 toolMinor = 0;
2173 size = 0;
2174 break;
2175 }
2176
2177 // Pressure
2178 float pressure;
2179 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002180 case Calibration::PressureCalibration::PHYSICAL:
2181 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002182 pressure = in.pressure * mPressureScale;
2183 break;
2184 default:
2185 pressure = in.isHovering ? 0 : 1;
2186 break;
2187 }
2188
2189 // Tilt and Orientation
2190 float tilt;
2191 float orientation;
2192 if (mHaveTilt) {
2193 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2194 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2195 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2196 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2197 } else {
2198 tilt = 0;
2199
2200 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002201 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002202 orientation = in.orientation * mOrientationScale;
2203 break;
Michael Wright227c5542020-07-02 18:30:52 +01002204 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002205 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2206 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2207 if (c1 != 0 || c2 != 0) {
2208 orientation = atan2f(c1, c2) * 0.5f;
2209 float confidence = hypotf(c1, c2);
2210 float scale = 1.0f + confidence / 16.0f;
2211 touchMajor *= scale;
2212 touchMinor /= scale;
2213 toolMajor *= scale;
2214 toolMinor /= scale;
2215 } else {
2216 orientation = 0;
2217 }
2218 break;
2219 }
2220 default:
2221 orientation = 0;
2222 }
2223 }
2224
2225 // Distance
2226 float distance;
2227 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002228 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002229 distance = in.distance * mDistanceScale;
2230 break;
2231 default:
2232 distance = 0;
2233 }
2234
2235 // Coverage
2236 int32_t rawLeft, rawTop, rawRight, rawBottom;
2237 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002238 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002239 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2240 rawRight = in.toolMinor & 0x0000ffff;
2241 rawBottom = in.toolMajor & 0x0000ffff;
2242 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2243 break;
2244 default:
2245 rawLeft = rawTop = rawRight = rawBottom = 0;
2246 break;
2247 }
2248
2249 // Adjust X,Y coords for device calibration
2250 // TODO: Adjust coverage coords?
2251 float xTransformed = in.x, yTransformed = in.y;
2252 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002253 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002254
2255 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 float left, top, right, bottom;
2257
2258 switch (mSurfaceOrientation) {
2259 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002260 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2261 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2262 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2263 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2264 orientation -= M_PI_2;
2265 if (mOrientedRanges.haveOrientation &&
2266 orientation < mOrientedRanges.orientation.min) {
2267 orientation +=
2268 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2269 }
2270 break;
2271 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002272 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2273 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2274 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2275 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2276 orientation -= M_PI;
2277 if (mOrientedRanges.haveOrientation &&
2278 orientation < mOrientedRanges.orientation.min) {
2279 orientation +=
2280 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2281 }
2282 break;
2283 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002284 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2285 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2286 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2287 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2288 orientation += M_PI_2;
2289 if (mOrientedRanges.haveOrientation &&
2290 orientation > mOrientedRanges.orientation.max) {
2291 orientation -=
2292 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2293 }
2294 break;
2295 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2297 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2298 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2299 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2300 break;
2301 }
2302
2303 // Write output coords.
2304 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2305 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002306 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2307 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002308 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2309 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2310 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2311 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2312 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2313 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2314 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002315 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002316 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2317 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2318 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2319 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2320 } else {
2321 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2322 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2323 }
2324
Chris Ye364fdb52020-08-05 15:07:56 -07002325 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002326 uint32_t id = in.id;
2327 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2328 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2329 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2330 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2331 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2332 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2333 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2334 }
2335
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002336 // Write output properties.
2337 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002338 properties.clear();
2339 properties.id = id;
2340 properties.toolType = in.toolType;
2341
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002342 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002344 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345 }
2346}
2347
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002348void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 PointerUsage pointerUsage) {
2350 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002351 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 mPointerUsage = pointerUsage;
2353 }
2354
2355 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002356 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002357 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 break;
Michael Wright227c5542020-07-02 18:30:52 +01002359 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002360 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 break;
Michael Wright227c5542020-07-02 18:30:52 +01002362 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002363 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002364 break;
Michael Wright227c5542020-07-02 18:30:52 +01002365 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 break;
2367 }
2368}
2369
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002370void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002372 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002373 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 break;
Michael Wright227c5542020-07-02 18:30:52 +01002375 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002376 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 break;
Michael Wright227c5542020-07-02 18:30:52 +01002378 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002379 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 break;
Michael Wright227c5542020-07-02 18:30:52 +01002381 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 break;
2383 }
2384
Michael Wright227c5542020-07-02 18:30:52 +01002385 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002386}
2387
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002388void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2389 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 // Update current gesture coordinates.
2391 bool cancelPreviousGesture, finishPreviousGesture;
2392 bool sendEvents =
2393 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2394 if (!sendEvents) {
2395 return;
2396 }
2397 if (finishPreviousGesture) {
2398 cancelPreviousGesture = false;
2399 }
2400
2401 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002402 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002403 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 if (finishPreviousGesture || cancelPreviousGesture) {
2405 mPointerController->clearSpots();
2406 }
2407
Michael Wright227c5542020-07-02 18:30:52 +01002408 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002409 setTouchSpots(mPointerGesture.currentGestureCoords,
2410 mPointerGesture.currentGestureIdToIndex,
2411 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002412 }
2413 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002414 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 }
2416
2417 // Show or hide the pointer if needed.
2418 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002419 case PointerGesture::Mode::NEUTRAL:
2420 case PointerGesture::Mode::QUIET:
2421 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2422 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002423 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002424 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 }
2426 break;
Michael Wright227c5542020-07-02 18:30:52 +01002427 case PointerGesture::Mode::TAP:
2428 case PointerGesture::Mode::TAP_DRAG:
2429 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2430 case PointerGesture::Mode::HOVER:
2431 case PointerGesture::Mode::PRESS:
2432 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002433 // Unfade the pointer when the current gesture manipulates the
2434 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002435 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 break;
Michael Wright227c5542020-07-02 18:30:52 +01002437 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002438 // Fade the pointer when the current gesture manipulates a different
2439 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002440 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002441 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002443 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002444 }
2445 break;
2446 }
2447
2448 // Send events!
2449 int32_t metaState = getContext()->getGlobalMetaState();
2450 int32_t buttonState = mCurrentCookedState.buttonState;
2451
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002452 uint32_t flags = 0;
2453
2454 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2455 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2456 }
2457
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 // Update last coordinates of pointers that have moved so that we observe the new
2459 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002460 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2461 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2462 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2463 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2464 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2465 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 bool moveNeeded = false;
2467 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2468 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2469 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2470 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2471 mPointerGesture.lastGestureIdBits.value);
2472 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2473 mPointerGesture.currentGestureCoords,
2474 mPointerGesture.currentGestureIdToIndex,
2475 mPointerGesture.lastGestureProperties,
2476 mPointerGesture.lastGestureCoords,
2477 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2478 if (buttonState != mLastCookedState.buttonState) {
2479 moveNeeded = true;
2480 }
2481 }
2482
2483 // Send motion events for all pointers that went up or were canceled.
2484 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2485 if (!dispatchedGestureIdBits.isEmpty()) {
2486 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002487 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2488 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002489 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2490 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2491 mPointerGesture.downTime);
2492
2493 dispatchedGestureIdBits.clear();
2494 } else {
2495 BitSet32 upGestureIdBits;
2496 if (finishPreviousGesture) {
2497 upGestureIdBits = dispatchedGestureIdBits;
2498 } else {
2499 upGestureIdBits.value =
2500 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2501 }
2502 while (!upGestureIdBits.isEmpty()) {
2503 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2504
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002505 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002506 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002507 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002508 mPointerGesture.lastGestureCoords,
2509 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2510 0, mPointerGesture.downTime);
2511
2512 dispatchedGestureIdBits.clearBit(id);
2513 }
2514 }
2515 }
2516
2517 // Send motion events for all pointers that moved.
2518 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002519 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002520 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002521 mPointerGesture.currentGestureProperties,
2522 mPointerGesture.currentGestureCoords,
2523 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2524 mPointerGesture.downTime);
2525 }
2526
2527 // Send motion events for all pointers that went down.
2528 if (down) {
2529 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2530 ~dispatchedGestureIdBits.value);
2531 while (!downGestureIdBits.isEmpty()) {
2532 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2533 dispatchedGestureIdBits.markBit(id);
2534
2535 if (dispatchedGestureIdBits.count() == 1) {
2536 mPointerGesture.downTime = when;
2537 }
2538
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002539 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002540 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002541 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002542 mPointerGesture.currentGestureCoords,
2543 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2544 0, mPointerGesture.downTime);
2545 }
2546 }
2547
2548 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002549 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002550 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2551 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552 mPointerGesture.currentGestureProperties,
2553 mPointerGesture.currentGestureCoords,
2554 mPointerGesture.currentGestureIdToIndex,
2555 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2556 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2557 // Synthesize a hover move event after all pointers go up to indicate that
2558 // the pointer is hovering again even if the user is not currently touching
2559 // the touch pad. This ensures that a view will receive a fresh hover enter
2560 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002561 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002562
2563 PointerProperties pointerProperties;
2564 pointerProperties.clear();
2565 pointerProperties.id = 0;
2566 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2567
2568 PointerCoords pointerCoords;
2569 pointerCoords.clear();
2570 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2571 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2572
2573 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002574 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002575 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002576 metaState, buttonState, MotionClassification::NONE,
2577 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2578 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002579 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002580 }
2581
2582 // Update state.
2583 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2584 if (!down) {
2585 mPointerGesture.lastGestureIdBits.clear();
2586 } else {
2587 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2588 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2589 uint32_t id = idBits.clearFirstMarkedBit();
2590 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2591 mPointerGesture.lastGestureProperties[index].copyFrom(
2592 mPointerGesture.currentGestureProperties[index]);
2593 mPointerGesture.lastGestureCoords[index].copyFrom(
2594 mPointerGesture.currentGestureCoords[index]);
2595 mPointerGesture.lastGestureIdToIndex[id] = index;
2596 }
2597 }
2598}
2599
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002600void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002601 // Cancel previously dispatches pointers.
2602 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2603 int32_t metaState = getContext()->getGlobalMetaState();
2604 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002605 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2606 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002607 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2608 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2609 0, 0, mPointerGesture.downTime);
2610 }
2611
2612 // Reset the current pointer gesture.
2613 mPointerGesture.reset();
2614 mPointerVelocityControl.reset();
2615
2616 // Remove any current spots.
2617 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002618 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002619 mPointerController->clearSpots();
2620 }
2621}
2622
2623bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2624 bool* outFinishPreviousGesture, bool isTimeout) {
2625 *outCancelPreviousGesture = false;
2626 *outFinishPreviousGesture = false;
2627
2628 // Handle TAP timeout.
2629 if (isTimeout) {
2630#if DEBUG_GESTURES
2631 ALOGD("Gestures: Processing timeout");
2632#endif
2633
Michael Wright227c5542020-07-02 18:30:52 +01002634 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002635 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2636 // The tap/drag timeout has not yet expired.
2637 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2638 mConfig.pointerGestureTapDragInterval);
2639 } else {
2640 // The tap is finished.
2641#if DEBUG_GESTURES
2642 ALOGD("Gestures: TAP finished");
2643#endif
2644 *outFinishPreviousGesture = true;
2645
2646 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002647 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002648 mPointerGesture.currentGestureIdBits.clear();
2649
2650 mPointerVelocityControl.reset();
2651 return true;
2652 }
2653 }
2654
2655 // We did not handle this timeout.
2656 return false;
2657 }
2658
2659 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2660 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2661
2662 // Update the velocity tracker.
2663 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002664 std::vector<VelocityTracker::Position> positions;
2665 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002666 uint32_t id = idBits.clearFirstMarkedBit();
2667 const RawPointerData::Pointer& pointer =
2668 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002669 float x = pointer.x * mPointerXMovementScale;
2670 float y = pointer.y * mPointerYMovementScale;
2671 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002672 }
2673 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2674 positions);
2675 }
2676
2677 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2678 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002679 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2680 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2681 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002682 mPointerGesture.resetTap();
2683 }
2684
2685 // Pick a new active touch id if needed.
2686 // Choose an arbitrary pointer that just went down, if there is one.
2687 // Otherwise choose an arbitrary remaining pointer.
2688 // This guarantees we always have an active touch id when there is at least one pointer.
2689 // We keep the same active touch id for as long as possible.
2690 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2691 int32_t activeTouchId = lastActiveTouchId;
2692 if (activeTouchId < 0) {
2693 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2694 activeTouchId = mPointerGesture.activeTouchId =
2695 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2696 mPointerGesture.firstTouchTime = when;
2697 }
2698 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2699 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2700 activeTouchId = mPointerGesture.activeTouchId =
2701 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2702 } else {
2703 activeTouchId = mPointerGesture.activeTouchId = -1;
2704 }
2705 }
2706
2707 // Determine whether we are in quiet time.
2708 bool isQuietTime = false;
2709 if (activeTouchId < 0) {
2710 mPointerGesture.resetQuietTime();
2711 } else {
2712 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2713 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002714 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2715 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2716 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002717 currentFingerCount < 2) {
2718 // Enter quiet time when exiting swipe or freeform state.
2719 // This is to prevent accidentally entering the hover state and flinging the
2720 // pointer when finishing a swipe and there is still one pointer left onscreen.
2721 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002722 } else if (mPointerGesture.lastGestureMode ==
2723 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002724 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2725 // Enter quiet time when releasing the button and there are still two or more
2726 // fingers down. This may indicate that one finger was used to press the button
2727 // but it has not gone up yet.
2728 isQuietTime = true;
2729 }
2730 if (isQuietTime) {
2731 mPointerGesture.quietTime = when;
2732 }
2733 }
2734 }
2735
2736 // Switch states based on button and pointer state.
2737 if (isQuietTime) {
2738 // Case 1: Quiet time. (QUIET)
2739#if DEBUG_GESTURES
2740 ALOGD("Gestures: QUIET for next %0.3fms",
2741 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2742#endif
Michael Wright227c5542020-07-02 18:30:52 +01002743 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002744 *outFinishPreviousGesture = true;
2745 }
2746
2747 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002748 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002749 mPointerGesture.currentGestureIdBits.clear();
2750
2751 mPointerVelocityControl.reset();
2752 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2753 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2754 // The pointer follows the active touch point.
2755 // Emit DOWN, MOVE, UP events at the pointer location.
2756 //
2757 // Only the active touch matters; other fingers are ignored. This policy helps
2758 // to handle the case where the user places a second finger on the touch pad
2759 // to apply the necessary force to depress an integrated button below the surface.
2760 // We don't want the second finger to be delivered to applications.
2761 //
2762 // For this to work well, we need to make sure to track the pointer that is really
2763 // active. If the user first puts one finger down to click then adds another
2764 // finger to drag then the active pointer should switch to the finger that is
2765 // being dragged.
2766#if DEBUG_GESTURES
2767 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2768 "currentFingerCount=%d",
2769 activeTouchId, currentFingerCount);
2770#endif
2771 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002772 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002773 *outFinishPreviousGesture = true;
2774 mPointerGesture.activeGestureId = 0;
2775 }
2776
2777 // Switch pointers if needed.
2778 // Find the fastest pointer and follow it.
2779 if (activeTouchId >= 0 && currentFingerCount > 1) {
2780 int32_t bestId = -1;
2781 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2782 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2783 uint32_t id = idBits.clearFirstMarkedBit();
2784 float vx, vy;
2785 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2786 float speed = hypotf(vx, vy);
2787 if (speed > bestSpeed) {
2788 bestId = id;
2789 bestSpeed = speed;
2790 }
2791 }
2792 }
2793 if (bestId >= 0 && bestId != activeTouchId) {
2794 mPointerGesture.activeTouchId = activeTouchId = bestId;
2795#if DEBUG_GESTURES
2796 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2797 "bestId=%d, bestSpeed=%0.3f",
2798 bestId, bestSpeed);
2799#endif
2800 }
2801 }
2802
2803 float deltaX = 0, deltaY = 0;
2804 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2805 const RawPointerData::Pointer& currentPointer =
2806 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2807 const RawPointerData::Pointer& lastPointer =
2808 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2809 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2810 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2811
2812 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2813 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2814
2815 // Move the pointer using a relative motion.
2816 // When using spots, the click will occur at the position of the anchor
2817 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002818 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002819 } else {
2820 mPointerVelocityControl.reset();
2821 }
2822
Prabir Pradhand7482e72021-03-09 13:54:55 -08002823 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824
Michael Wright227c5542020-07-02 18:30:52 +01002825 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826 mPointerGesture.currentGestureIdBits.clear();
2827 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2828 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2829 mPointerGesture.currentGestureProperties[0].clear();
2830 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2831 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2832 mPointerGesture.currentGestureCoords[0].clear();
2833 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2834 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2835 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2836 } else if (currentFingerCount == 0) {
2837 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002838 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002839 *outFinishPreviousGesture = true;
2840 }
2841
2842 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2843 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2844 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002845 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2846 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002847 lastFingerCount == 1) {
2848 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002849 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002850 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2851 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2852#if DEBUG_GESTURES
2853 ALOGD("Gestures: TAP");
2854#endif
2855
2856 mPointerGesture.tapUpTime = when;
2857 getContext()->requestTimeoutAtTime(when +
2858 mConfig.pointerGestureTapDragInterval);
2859
2860 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002861 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002862 mPointerGesture.currentGestureIdBits.clear();
2863 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2864 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2865 mPointerGesture.currentGestureProperties[0].clear();
2866 mPointerGesture.currentGestureProperties[0].id =
2867 mPointerGesture.activeGestureId;
2868 mPointerGesture.currentGestureProperties[0].toolType =
2869 AMOTION_EVENT_TOOL_TYPE_FINGER;
2870 mPointerGesture.currentGestureCoords[0].clear();
2871 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2872 mPointerGesture.tapX);
2873 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2874 mPointerGesture.tapY);
2875 mPointerGesture.currentGestureCoords[0]
2876 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2877
2878 tapped = true;
2879 } else {
2880#if DEBUG_GESTURES
2881 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2882 y - mPointerGesture.tapY);
2883#endif
2884 }
2885 } else {
2886#if DEBUG_GESTURES
2887 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2888 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2889 (when - mPointerGesture.tapDownTime) * 0.000001f);
2890 } else {
2891 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2892 }
2893#endif
2894 }
2895 }
2896
2897 mPointerVelocityControl.reset();
2898
2899 if (!tapped) {
2900#if DEBUG_GESTURES
2901 ALOGD("Gestures: NEUTRAL");
2902#endif
2903 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002904 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002905 mPointerGesture.currentGestureIdBits.clear();
2906 }
2907 } else if (currentFingerCount == 1) {
2908 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2909 // The pointer follows the active touch point.
2910 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2911 // When in TAP_DRAG, emit MOVE events at the pointer location.
2912 ALOG_ASSERT(activeTouchId >= 0);
2913
Michael Wright227c5542020-07-02 18:30:52 +01002914 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2915 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002917 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002918 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2919 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002920 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002921 } else {
2922#if DEBUG_GESTURES
2923 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2924 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2925#endif
2926 }
2927 } else {
2928#if DEBUG_GESTURES
2929 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2930 (when - mPointerGesture.tapUpTime) * 0.000001f);
2931#endif
2932 }
Michael Wright227c5542020-07-02 18:30:52 +01002933 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2934 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002935 }
2936
2937 float deltaX = 0, deltaY = 0;
2938 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2939 const RawPointerData::Pointer& currentPointer =
2940 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2941 const RawPointerData::Pointer& lastPointer =
2942 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2943 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2944 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2945
2946 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2947 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2948
2949 // Move the pointer using a relative motion.
2950 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002951 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 } else {
2953 mPointerVelocityControl.reset();
2954 }
2955
2956 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002957 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958#if DEBUG_GESTURES
2959 ALOGD("Gestures: TAP_DRAG");
2960#endif
2961 down = true;
2962 } else {
2963#if DEBUG_GESTURES
2964 ALOGD("Gestures: HOVER");
2965#endif
Michael Wright227c5542020-07-02 18:30:52 +01002966 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002967 *outFinishPreviousGesture = true;
2968 }
2969 mPointerGesture.activeGestureId = 0;
2970 down = false;
2971 }
2972
Prabir Pradhand7482e72021-03-09 13:54:55 -08002973 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974
2975 mPointerGesture.currentGestureIdBits.clear();
2976 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2977 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2978 mPointerGesture.currentGestureProperties[0].clear();
2979 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2980 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2981 mPointerGesture.currentGestureCoords[0].clear();
2982 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2983 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2984 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2985 down ? 1.0f : 0.0f);
2986
2987 if (lastFingerCount == 0 && currentFingerCount != 0) {
2988 mPointerGesture.resetTap();
2989 mPointerGesture.tapDownTime = when;
2990 mPointerGesture.tapX = x;
2991 mPointerGesture.tapY = y;
2992 }
2993 } else {
2994 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2995 // We need to provide feedback for each finger that goes down so we cannot wait
2996 // for the fingers to move before deciding what to do.
2997 //
2998 // The ambiguous case is deciding what to do when there are two fingers down but they
2999 // have not moved enough to determine whether they are part of a drag or part of a
3000 // freeform gesture, or just a press or long-press at the pointer location.
3001 //
3002 // When there are two fingers we start with the PRESS hypothesis and we generate a
3003 // down at the pointer location.
3004 //
3005 // When the two fingers move enough or when additional fingers are added, we make
3006 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3007 ALOG_ASSERT(activeTouchId >= 0);
3008
3009 bool settled = when >=
3010 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003011 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3012 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3013 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003014 *outFinishPreviousGesture = true;
3015 } else if (!settled && currentFingerCount > lastFingerCount) {
3016 // Additional pointers have gone down but not yet settled.
3017 // Reset the gesture.
3018#if DEBUG_GESTURES
3019 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3020 "settle time remaining %0.3fms",
3021 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3022 when) * 0.000001f);
3023#endif
3024 *outCancelPreviousGesture = true;
3025 } else {
3026 // Continue previous gesture.
3027 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3028 }
3029
3030 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003031 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003032 mPointerGesture.activeGestureId = 0;
3033 mPointerGesture.referenceIdBits.clear();
3034 mPointerVelocityControl.reset();
3035
3036 // Use the centroid and pointer location as the reference points for the gesture.
3037#if DEBUG_GESTURES
3038 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3039 "settle time remaining %0.3fms",
3040 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3041 when) * 0.000001f);
3042#endif
3043 mCurrentRawState.rawPointerData
3044 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3045 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003046 auto [x, y] = getMouseCursorPosition();
3047 mPointerGesture.referenceGestureX = x;
3048 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003049 }
3050
3051 // Clear the reference deltas for fingers not yet included in the reference calculation.
3052 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3053 ~mPointerGesture.referenceIdBits.value);
3054 !idBits.isEmpty();) {
3055 uint32_t id = idBits.clearFirstMarkedBit();
3056 mPointerGesture.referenceDeltas[id].dx = 0;
3057 mPointerGesture.referenceDeltas[id].dy = 0;
3058 }
3059 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3060
3061 // Add delta for all fingers and calculate a common movement delta.
3062 float commonDeltaX = 0, commonDeltaY = 0;
3063 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3064 mCurrentCookedState.fingerIdBits.value);
3065 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3066 bool first = (idBits == commonIdBits);
3067 uint32_t id = idBits.clearFirstMarkedBit();
3068 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3069 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3070 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3071 delta.dx += cpd.x - lpd.x;
3072 delta.dy += cpd.y - lpd.y;
3073
3074 if (first) {
3075 commonDeltaX = delta.dx;
3076 commonDeltaY = delta.dy;
3077 } else {
3078 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3079 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3080 }
3081 }
3082
3083 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003084 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003085 float dist[MAX_POINTER_ID + 1];
3086 int32_t distOverThreshold = 0;
3087 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3088 uint32_t id = idBits.clearFirstMarkedBit();
3089 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3090 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3091 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3092 distOverThreshold += 1;
3093 }
3094 }
3095
3096 // Only transition when at least two pointers have moved further than
3097 // the minimum distance threshold.
3098 if (distOverThreshold >= 2) {
3099 if (currentFingerCount > 2) {
3100 // There are more than two pointers, switch to FREEFORM.
3101#if DEBUG_GESTURES
3102 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3103 currentFingerCount);
3104#endif
3105 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003106 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003107 } else {
3108 // There are exactly two pointers.
3109 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3110 uint32_t id1 = idBits.clearFirstMarkedBit();
3111 uint32_t id2 = idBits.firstMarkedBit();
3112 const RawPointerData::Pointer& p1 =
3113 mCurrentRawState.rawPointerData.pointerForId(id1);
3114 const RawPointerData::Pointer& p2 =
3115 mCurrentRawState.rawPointerData.pointerForId(id2);
3116 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3117 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3118 // There are two pointers but they are too far apart for a SWIPE,
3119 // switch to FREEFORM.
3120#if DEBUG_GESTURES
3121 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3122 mutualDistance, mPointerGestureMaxSwipeWidth);
3123#endif
3124 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003125 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003126 } else {
3127 // There are two pointers. Wait for both pointers to start moving
3128 // before deciding whether this is a SWIPE or FREEFORM gesture.
3129 float dist1 = dist[id1];
3130 float dist2 = dist[id2];
3131 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3132 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3133 // Calculate the dot product of the displacement vectors.
3134 // When the vectors are oriented in approximately the same direction,
3135 // the angle betweeen them is near zero and the cosine of the angle
3136 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3137 // mag(v2).
3138 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3139 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3140 float dx1 = delta1.dx * mPointerXZoomScale;
3141 float dy1 = delta1.dy * mPointerYZoomScale;
3142 float dx2 = delta2.dx * mPointerXZoomScale;
3143 float dy2 = delta2.dy * mPointerYZoomScale;
3144 float dot = dx1 * dx2 + dy1 * dy2;
3145 float cosine = dot / (dist1 * dist2); // denominator always > 0
3146 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3147 // Pointers are moving in the same direction. Switch to SWIPE.
3148#if DEBUG_GESTURES
3149 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3150 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3151 "cosine %0.3f >= %0.3f",
3152 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3153 mConfig.pointerGestureMultitouchMinDistance, cosine,
3154 mConfig.pointerGestureSwipeTransitionAngleCosine);
3155#endif
Michael Wright227c5542020-07-02 18:30:52 +01003156 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003157 } else {
3158 // Pointers are moving in different directions. Switch to FREEFORM.
3159#if DEBUG_GESTURES
3160 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3161 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3162 "cosine %0.3f < %0.3f",
3163 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3164 mConfig.pointerGestureMultitouchMinDistance, cosine,
3165 mConfig.pointerGestureSwipeTransitionAngleCosine);
3166#endif
3167 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003168 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003169 }
3170 }
3171 }
3172 }
3173 }
Michael Wright227c5542020-07-02 18:30:52 +01003174 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003175 // Switch from SWIPE to FREEFORM if additional pointers go down.
3176 // Cancel previous gesture.
3177 if (currentFingerCount > 2) {
3178#if DEBUG_GESTURES
3179 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3180 currentFingerCount);
3181#endif
3182 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003183 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003184 }
3185 }
3186
3187 // Move the reference points based on the overall group motion of the fingers
3188 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003189 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003190 (commonDeltaX || commonDeltaY)) {
3191 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3192 uint32_t id = idBits.clearFirstMarkedBit();
3193 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3194 delta.dx = 0;
3195 delta.dy = 0;
3196 }
3197
3198 mPointerGesture.referenceTouchX += commonDeltaX;
3199 mPointerGesture.referenceTouchY += commonDeltaY;
3200
3201 commonDeltaX *= mPointerXMovementScale;
3202 commonDeltaY *= mPointerYMovementScale;
3203
3204 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3205 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3206
3207 mPointerGesture.referenceGestureX += commonDeltaX;
3208 mPointerGesture.referenceGestureY += commonDeltaY;
3209 }
3210
3211 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003212 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3213 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003214 // PRESS or SWIPE mode.
3215#if DEBUG_GESTURES
3216 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3217 "activeGestureId=%d, currentTouchPointerCount=%d",
3218 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3219#endif
3220 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3221
3222 mPointerGesture.currentGestureIdBits.clear();
3223 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3224 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3225 mPointerGesture.currentGestureProperties[0].clear();
3226 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3227 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3228 mPointerGesture.currentGestureCoords[0].clear();
3229 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3230 mPointerGesture.referenceGestureX);
3231 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3232 mPointerGesture.referenceGestureY);
3233 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003234 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003235 // FREEFORM mode.
3236#if DEBUG_GESTURES
3237 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3238 "activeGestureId=%d, currentTouchPointerCount=%d",
3239 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3240#endif
3241 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3242
3243 mPointerGesture.currentGestureIdBits.clear();
3244
3245 BitSet32 mappedTouchIdBits;
3246 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003247 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003248 // Initially, assign the active gesture id to the active touch point
3249 // if there is one. No other touch id bits are mapped yet.
3250 if (!*outCancelPreviousGesture) {
3251 mappedTouchIdBits.markBit(activeTouchId);
3252 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3253 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3254 mPointerGesture.activeGestureId;
3255 } else {
3256 mPointerGesture.activeGestureId = -1;
3257 }
3258 } else {
3259 // Otherwise, assume we mapped all touches from the previous frame.
3260 // Reuse all mappings that are still applicable.
3261 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3262 mCurrentCookedState.fingerIdBits.value;
3263 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3264
3265 // Check whether we need to choose a new active gesture id because the
3266 // current went went up.
3267 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3268 ~mCurrentCookedState.fingerIdBits.value);
3269 !upTouchIdBits.isEmpty();) {
3270 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3271 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3272 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3273 mPointerGesture.activeGestureId = -1;
3274 break;
3275 }
3276 }
3277 }
3278
3279#if DEBUG_GESTURES
3280 ALOGD("Gestures: FREEFORM follow up "
3281 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3282 "activeGestureId=%d",
3283 mappedTouchIdBits.value, usedGestureIdBits.value,
3284 mPointerGesture.activeGestureId);
3285#endif
3286
3287 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3288 for (uint32_t i = 0; i < currentFingerCount; i++) {
3289 uint32_t touchId = idBits.clearFirstMarkedBit();
3290 uint32_t gestureId;
3291 if (!mappedTouchIdBits.hasBit(touchId)) {
3292 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3293 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3294#if DEBUG_GESTURES
3295 ALOGD("Gestures: FREEFORM "
3296 "new mapping for touch id %d -> gesture id %d",
3297 touchId, gestureId);
3298#endif
3299 } else {
3300 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3301#if DEBUG_GESTURES
3302 ALOGD("Gestures: FREEFORM "
3303 "existing mapping for touch id %d -> gesture id %d",
3304 touchId, gestureId);
3305#endif
3306 }
3307 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3308 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3309
3310 const RawPointerData::Pointer& pointer =
3311 mCurrentRawState.rawPointerData.pointerForId(touchId);
3312 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3313 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3314 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3315
3316 mPointerGesture.currentGestureProperties[i].clear();
3317 mPointerGesture.currentGestureProperties[i].id = gestureId;
3318 mPointerGesture.currentGestureProperties[i].toolType =
3319 AMOTION_EVENT_TOOL_TYPE_FINGER;
3320 mPointerGesture.currentGestureCoords[i].clear();
3321 mPointerGesture.currentGestureCoords[i]
3322 .setAxisValue(AMOTION_EVENT_AXIS_X,
3323 mPointerGesture.referenceGestureX + deltaX);
3324 mPointerGesture.currentGestureCoords[i]
3325 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3326 mPointerGesture.referenceGestureY + deltaY);
3327 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3328 1.0f);
3329 }
3330
3331 if (mPointerGesture.activeGestureId < 0) {
3332 mPointerGesture.activeGestureId =
3333 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3334#if DEBUG_GESTURES
3335 ALOGD("Gestures: FREEFORM new "
3336 "activeGestureId=%d",
3337 mPointerGesture.activeGestureId);
3338#endif
3339 }
3340 }
3341 }
3342
3343 mPointerController->setButtonState(mCurrentRawState.buttonState);
3344
3345#if DEBUG_GESTURES
3346 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3347 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3348 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3349 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3350 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3351 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3352 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3353 uint32_t id = idBits.clearFirstMarkedBit();
3354 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3355 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3356 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3357 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3358 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3359 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3360 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3361 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3362 }
3363 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3364 uint32_t id = idBits.clearFirstMarkedBit();
3365 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3366 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3367 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3368 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3369 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3370 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3371 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3372 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3373 }
3374#endif
3375 return true;
3376}
3377
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003378void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003379 mPointerSimple.currentCoords.clear();
3380 mPointerSimple.currentProperties.clear();
3381
3382 bool down, hovering;
3383 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3384 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3385 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003386 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3387 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003388
3389 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3390 down = !hovering;
3391
Prabir Pradhand7482e72021-03-09 13:54:55 -08003392 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003393 mPointerSimple.currentCoords.copyFrom(
3394 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3395 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3396 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3397 mPointerSimple.currentProperties.id = 0;
3398 mPointerSimple.currentProperties.toolType =
3399 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3400 } else {
3401 down = false;
3402 hovering = false;
3403 }
3404
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003405 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003406}
3407
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003408void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3409 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003410}
3411
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003412void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003413 mPointerSimple.currentCoords.clear();
3414 mPointerSimple.currentProperties.clear();
3415
3416 bool down, hovering;
3417 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3418 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3419 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3420 float deltaX = 0, deltaY = 0;
3421 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3422 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3423 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3424 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3425 mPointerXMovementScale;
3426 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3427 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3428 mPointerYMovementScale;
3429
3430 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3431 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3432
Prabir Pradhand7482e72021-03-09 13:54:55 -08003433 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003434 } else {
3435 mPointerVelocityControl.reset();
3436 }
3437
3438 down = isPointerDown(mCurrentRawState.buttonState);
3439 hovering = !down;
3440
Prabir Pradhand7482e72021-03-09 13:54:55 -08003441 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003442 mPointerSimple.currentCoords.copyFrom(
3443 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3444 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3445 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3446 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3447 hovering ? 0.0f : 1.0f);
3448 mPointerSimple.currentProperties.id = 0;
3449 mPointerSimple.currentProperties.toolType =
3450 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3451 } else {
3452 mPointerVelocityControl.reset();
3453
3454 down = false;
3455 hovering = false;
3456 }
3457
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003458 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003459}
3460
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003461void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3462 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003463
3464 mPointerVelocityControl.reset();
3465}
3466
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003467void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3468 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003470
3471 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003472 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003473 mPointerController->clearSpots();
3474 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003475 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003476 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003477 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003478 }
Garfield Tan9514d782020-11-10 16:37:23 -08003479 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003480
Prabir Pradhand7482e72021-03-09 13:54:55 -08003481 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003482
3483 if (mPointerSimple.down && !down) {
3484 mPointerSimple.down = false;
3485
3486 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003487 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3488 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003489 mLastRawState.buttonState, MotionClassification::NONE,
3490 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3491 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3492 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3493 /* videoFrames */ {});
3494 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003495 }
3496
3497 if (mPointerSimple.hovering && !hovering) {
3498 mPointerSimple.hovering = false;
3499
3500 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003501 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3502 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3503 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003504 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3505 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3506 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3507 /* videoFrames */ {});
3508 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509 }
3510
3511 if (down) {
3512 if (!mPointerSimple.down) {
3513 mPointerSimple.down = true;
3514 mPointerSimple.downTime = when;
3515
3516 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003517 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003518 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3519 metaState, mCurrentRawState.buttonState,
3520 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3521 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3522 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3523 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3524 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003525 }
3526
3527 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003528 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3529 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003530 mCurrentRawState.buttonState, MotionClassification::NONE,
3531 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3532 &mPointerSimple.currentCoords, mOrientedXPrecision,
3533 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3534 mPointerSimple.downTime, /* videoFrames */ {});
3535 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003536 }
3537
3538 if (hovering) {
3539 if (!mPointerSimple.hovering) {
3540 mPointerSimple.hovering = true;
3541
3542 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003543 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003544 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3545 metaState, mCurrentRawState.buttonState,
3546 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3547 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3548 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3549 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3550 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003551 }
3552
3553 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003554 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3555 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3556 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003557 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3558 &mPointerSimple.currentCoords, mOrientedXPrecision,
3559 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3560 mPointerSimple.downTime, /* videoFrames */ {});
3561 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003562 }
3563
3564 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3565 float vscroll = mCurrentRawState.rawVScroll;
3566 float hscroll = mCurrentRawState.rawHScroll;
3567 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3568 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3569
3570 // Send scroll.
3571 PointerCoords pointerCoords;
3572 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3573 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3574 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3575
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003576 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3577 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003578 mCurrentRawState.buttonState, MotionClassification::NONE,
3579 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3580 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3581 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3582 /* videoFrames */ {});
3583 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003584 }
3585
3586 // Save state.
3587 if (down || hovering) {
3588 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3589 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3590 } else {
3591 mPointerSimple.reset();
3592 }
3593}
3594
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003595void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003596 mPointerSimple.currentCoords.clear();
3597 mPointerSimple.currentProperties.clear();
3598
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003599 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003600}
3601
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003602void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3603 uint32_t source, int32_t action, int32_t actionButton,
3604 int32_t flags, int32_t metaState, int32_t buttonState,
3605 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606 const PointerCoords* coords, const uint32_t* idToIndex,
3607 BitSet32 idBits, int32_t changedId, float xPrecision,
3608 float yPrecision, nsecs_t downTime) {
3609 PointerCoords pointerCoords[MAX_POINTERS];
3610 PointerProperties pointerProperties[MAX_POINTERS];
3611 uint32_t pointerCount = 0;
3612 while (!idBits.isEmpty()) {
3613 uint32_t id = idBits.clearFirstMarkedBit();
3614 uint32_t index = idToIndex[id];
3615 pointerProperties[pointerCount].copyFrom(properties[index]);
3616 pointerCoords[pointerCount].copyFrom(coords[index]);
3617
3618 if (changedId >= 0 && id == uint32_t(changedId)) {
3619 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3620 }
3621
3622 pointerCount += 1;
3623 }
3624
3625 ALOG_ASSERT(pointerCount != 0);
3626
3627 if (changedId >= 0 && pointerCount == 1) {
3628 // Replace initial down and final up action.
3629 // We can compare the action without masking off the changed pointer index
3630 // because we know the index is 0.
3631 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3632 action = AMOTION_EVENT_ACTION_DOWN;
3633 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003634 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3635 action = AMOTION_EVENT_ACTION_CANCEL;
3636 } else {
3637 action = AMOTION_EVENT_ACTION_UP;
3638 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003639 } else {
3640 // Can't happen.
3641 ALOG_ASSERT(false);
3642 }
3643 }
3644 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3645 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003646 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003647 auto [x, y] = getMouseCursorPosition();
3648 xCursorPosition = x;
3649 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003650 }
3651 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3652 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003653 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003654 std::for_each(frames.begin(), frames.end(),
3655 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003656 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3657 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003658 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3659 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3660 downTime, std::move(frames));
3661 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003662}
3663
3664bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3665 const PointerCoords* inCoords,
3666 const uint32_t* inIdToIndex,
3667 PointerProperties* outProperties,
3668 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3669 BitSet32 idBits) const {
3670 bool changed = false;
3671 while (!idBits.isEmpty()) {
3672 uint32_t id = idBits.clearFirstMarkedBit();
3673 uint32_t inIndex = inIdToIndex[id];
3674 uint32_t outIndex = outIdToIndex[id];
3675
3676 const PointerProperties& curInProperties = inProperties[inIndex];
3677 const PointerCoords& curInCoords = inCoords[inIndex];
3678 PointerProperties& curOutProperties = outProperties[outIndex];
3679 PointerCoords& curOutCoords = outCoords[outIndex];
3680
3681 if (curInProperties != curOutProperties) {
3682 curOutProperties.copyFrom(curInProperties);
3683 changed = true;
3684 }
3685
3686 if (curInCoords != curOutCoords) {
3687 curOutCoords.copyFrom(curInCoords);
3688 changed = true;
3689 }
3690 }
3691 return changed;
3692}
3693
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003694void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3695 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3696 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003697}
3698
Arthur Hung4197f6b2020-03-16 15:39:59 +08003699// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003700void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003701 // Scale to surface coordinate.
3702 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3703 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3704
arthurhunga36b28e2020-12-29 20:28:15 +08003705 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3706 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3707
Arthur Hung4197f6b2020-03-16 15:39:59 +08003708 // Rotate to surface coordinate.
3709 // 0 - no swap and reverse.
3710 // 90 - swap x/y and reverse y.
3711 // 180 - reverse x, y.
3712 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003713 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003714 case DISPLAY_ORIENTATION_0:
3715 x = xScaled + mXTranslate;
3716 y = yScaled + mYTranslate;
3717 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003718 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003719 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003720 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003721 break;
3722 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003723 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3724 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003725 break;
3726 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003727 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003728 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003729 break;
3730 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003731 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003732 }
3733}
3734
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003735bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003736 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3737 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3738
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003739 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003740 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003741 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003742 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003743}
3744
3745const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3746 for (const VirtualKey& virtualKey : mVirtualKeys) {
3747#if DEBUG_VIRTUAL_KEYS
3748 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3749 "left=%d, top=%d, right=%d, bottom=%d",
3750 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3751 virtualKey.hitRight, virtualKey.hitBottom);
3752#endif
3753
3754 if (virtualKey.isHit(x, y)) {
3755 return &virtualKey;
3756 }
3757 }
3758
3759 return nullptr;
3760}
3761
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003762void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3763 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3764 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003765
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003766 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003767
3768 if (currentPointerCount == 0) {
3769 // No pointers to assign.
3770 return;
3771 }
3772
3773 if (lastPointerCount == 0) {
3774 // All pointers are new.
3775 for (uint32_t i = 0; i < currentPointerCount; i++) {
3776 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003777 current.rawPointerData.pointers[i].id = id;
3778 current.rawPointerData.idToIndex[id] = i;
3779 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003780 }
3781 return;
3782 }
3783
3784 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003785 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003786 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003787 uint32_t id = last.rawPointerData.pointers[0].id;
3788 current.rawPointerData.pointers[0].id = id;
3789 current.rawPointerData.idToIndex[id] = 0;
3790 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003791 return;
3792 }
3793
3794 // General case.
3795 // We build a heap of squared euclidean distances between current and last pointers
3796 // associated with the current and last pointer indices. Then, we find the best
3797 // match (by distance) for each current pointer.
3798 // The pointers must have the same tool type but it is possible for them to
3799 // transition from hovering to touching or vice-versa while retaining the same id.
3800 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3801
3802 uint32_t heapSize = 0;
3803 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3804 currentPointerIndex++) {
3805 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3806 lastPointerIndex++) {
3807 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003808 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003809 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003810 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003811 if (currentPointer.toolType == lastPointer.toolType) {
3812 int64_t deltaX = currentPointer.x - lastPointer.x;
3813 int64_t deltaY = currentPointer.y - lastPointer.y;
3814
3815 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3816
3817 // Insert new element into the heap (sift up).
3818 heap[heapSize].currentPointerIndex = currentPointerIndex;
3819 heap[heapSize].lastPointerIndex = lastPointerIndex;
3820 heap[heapSize].distance = distance;
3821 heapSize += 1;
3822 }
3823 }
3824 }
3825
3826 // Heapify
3827 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3828 startIndex -= 1;
3829 for (uint32_t parentIndex = startIndex;;) {
3830 uint32_t childIndex = parentIndex * 2 + 1;
3831 if (childIndex >= heapSize) {
3832 break;
3833 }
3834
3835 if (childIndex + 1 < heapSize &&
3836 heap[childIndex + 1].distance < heap[childIndex].distance) {
3837 childIndex += 1;
3838 }
3839
3840 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3841 break;
3842 }
3843
3844 swap(heap[parentIndex], heap[childIndex]);
3845 parentIndex = childIndex;
3846 }
3847 }
3848
3849#if DEBUG_POINTER_ASSIGNMENT
3850 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3851 for (size_t i = 0; i < heapSize; i++) {
3852 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3853 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3854 }
3855#endif
3856
3857 // Pull matches out by increasing order of distance.
3858 // To avoid reassigning pointers that have already been matched, the loop keeps track
3859 // of which last and current pointers have been matched using the matchedXXXBits variables.
3860 // It also tracks the used pointer id bits.
3861 BitSet32 matchedLastBits(0);
3862 BitSet32 matchedCurrentBits(0);
3863 BitSet32 usedIdBits(0);
3864 bool first = true;
3865 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3866 while (heapSize > 0) {
3867 if (first) {
3868 // The first time through the loop, we just consume the root element of
3869 // the heap (the one with smallest distance).
3870 first = false;
3871 } else {
3872 // Previous iterations consumed the root element of the heap.
3873 // Pop root element off of the heap (sift down).
3874 heap[0] = heap[heapSize];
3875 for (uint32_t parentIndex = 0;;) {
3876 uint32_t childIndex = parentIndex * 2 + 1;
3877 if (childIndex >= heapSize) {
3878 break;
3879 }
3880
3881 if (childIndex + 1 < heapSize &&
3882 heap[childIndex + 1].distance < heap[childIndex].distance) {
3883 childIndex += 1;
3884 }
3885
3886 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3887 break;
3888 }
3889
3890 swap(heap[parentIndex], heap[childIndex]);
3891 parentIndex = childIndex;
3892 }
3893
3894#if DEBUG_POINTER_ASSIGNMENT
3895 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003896 for (size_t j = 0; j < heapSize; j++) {
3897 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3898 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003899 }
3900#endif
3901 }
3902
3903 heapSize -= 1;
3904
3905 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3906 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3907
3908 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3909 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3910
3911 matchedCurrentBits.markBit(currentPointerIndex);
3912 matchedLastBits.markBit(lastPointerIndex);
3913
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003914 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3915 current.rawPointerData.pointers[currentPointerIndex].id = id;
3916 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3917 current.rawPointerData.markIdBit(id,
3918 current.rawPointerData.isHovering(
3919 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003920 usedIdBits.markBit(id);
3921
3922#if DEBUG_POINTER_ASSIGNMENT
3923 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3924 ", distance=%" PRIu64,
3925 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3926#endif
3927 break;
3928 }
3929 }
3930
3931 // Assign fresh ids to pointers that were not matched in the process.
3932 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3933 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3934 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3935
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003936 current.rawPointerData.pointers[currentPointerIndex].id = id;
3937 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3938 current.rawPointerData.markIdBit(id,
3939 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003940
3941#if DEBUG_POINTER_ASSIGNMENT
3942 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3943#endif
3944 }
3945}
3946
3947int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3948 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3949 return AKEY_STATE_VIRTUAL;
3950 }
3951
3952 for (const VirtualKey& virtualKey : mVirtualKeys) {
3953 if (virtualKey.keyCode == keyCode) {
3954 return AKEY_STATE_UP;
3955 }
3956 }
3957
3958 return AKEY_STATE_UNKNOWN;
3959}
3960
3961int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3962 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3963 return AKEY_STATE_VIRTUAL;
3964 }
3965
3966 for (const VirtualKey& virtualKey : mVirtualKeys) {
3967 if (virtualKey.scanCode == scanCode) {
3968 return AKEY_STATE_UP;
3969 }
3970 }
3971
3972 return AKEY_STATE_UNKNOWN;
3973}
3974
3975bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3976 const int32_t* keyCodes, uint8_t* outFlags) {
3977 for (const VirtualKey& virtualKey : mVirtualKeys) {
3978 for (size_t i = 0; i < numCodes; i++) {
3979 if (virtualKey.keyCode == keyCodes[i]) {
3980 outFlags[i] = 1;
3981 }
3982 }
3983 }
3984
3985 return true;
3986}
3987
3988std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3989 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003990 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003991 return std::make_optional(mPointerController->getDisplayId());
3992 } else {
3993 return std::make_optional(mViewport.displayId);
3994 }
3995 }
3996 return std::nullopt;
3997}
3998
Prabir Pradhand7482e72021-03-09 13:54:55 -08003999void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
4000 if (isPerWindowInputRotationEnabled()) {
4001 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4002 // space that is oriented with the viewport.
4003 rotateDelta(mViewport.orientation, &dx, &dy);
4004 }
4005
4006 mPointerController->move(dx, dy);
4007}
4008
4009std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4010 float x = 0;
4011 float y = 0;
4012 mPointerController->getPosition(&x, &y);
4013
4014 if (!isPerWindowInputRotationEnabled()) return {x, y};
4015 if (!mViewport.isValid()) return {x, y};
4016
4017 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4018 // to InputReader's un-rotated coordinate space.
4019 const int32_t orientation = getInverseRotation(mViewport.orientation);
4020 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4021 return {x, y};
4022}
4023
4024void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4025 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4026 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4027 // coordinate space that is oriented with the viewport.
4028 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4029 }
4030
4031 mPointerController->setPosition(x, y);
4032}
4033
4034void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4035 BitSet32 spotIdBits, int32_t displayId) {
4036 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4037
4038 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4039 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4040 float x = spotCoords[index].getX();
4041 float y = spotCoords[index].getY();
4042 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4043
4044 if (isPerWindowInputRotationEnabled()) {
4045 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4046 // coordinate space.
4047 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4048 }
4049
4050 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4051 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4052 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4053 }
4054
4055 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4056}
4057
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004058} // namespace android