blob: fbb4db055fa28ce72487f4744290a83f510ed5ba [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
chaviw3277faf2021-05-19 16:45:23 -050021#include <ftl/NamedEnum.h>
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070022#include "TouchInputMapper.h"
23
24#include "CursorButtonAccumulator.h"
25#include "CursorScrollAccumulator.h"
26#include "TouchButtonAccumulator.h"
27#include "TouchCursorInputMapperCommon.h"
28
29namespace android {
30
31// --- Constants ---
32
33// Maximum amount of latency to add to touch events while waiting for data from an
34// external stylus.
35static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
36
37// Maximum amount of time to wait on touch data before pushing out new pressure data.
38static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
39
40// Artificial latency on synthetic events created from stylus data without corresponding touch
41// data.
42static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
43
44// --- Static Definitions ---
45
46template <typename T>
47inline static void swap(T& a, T& b) {
48 T temp = a;
49 a = b;
50 b = temp;
51}
52
53static float calculateCommonVector(float a, float b) {
54 if (a > 0 && b > 0) {
55 return a < b ? a : b;
56 } else if (a < 0 && b < 0) {
57 return a > b ? a : b;
58 } else {
59 return 0;
60 }
61}
62
63inline static float distance(float x1, float y1, float x2, float y2) {
64 return hypotf(x1 - x2, y1 - y2);
65}
66
67inline static int32_t signExtendNybble(int32_t value) {
68 return value >= 8 ? value - 16 : value;
69}
70
71// --- RawPointerAxes ---
72
73RawPointerAxes::RawPointerAxes() {
74 clear();
75}
76
77void RawPointerAxes::clear() {
78 x.clear();
79 y.clear();
80 pressure.clear();
81 touchMajor.clear();
82 touchMinor.clear();
83 toolMajor.clear();
84 toolMinor.clear();
85 orientation.clear();
86 distance.clear();
87 tiltX.clear();
88 tiltY.clear();
89 trackingId.clear();
90 slot.clear();
91}
92
93// --- RawPointerData ---
94
95RawPointerData::RawPointerData() {
96 clear();
97}
98
99void RawPointerData::clear() {
100 pointerCount = 0;
101 clearIdBits();
102}
103
104void RawPointerData::copyFrom(const RawPointerData& other) {
105 pointerCount = other.pointerCount;
106 hoveringIdBits = other.hoveringIdBits;
107 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800108 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109
110 for (uint32_t i = 0; i < pointerCount; i++) {
111 pointers[i] = other.pointers[i];
112
113 int id = pointers[i].id;
114 idToIndex[id] = other.idToIndex[id];
115 }
116}
117
118void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
119 float x = 0, y = 0;
120 uint32_t count = touchingIdBits.count();
121 if (count) {
122 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
123 uint32_t id = idBits.clearFirstMarkedBit();
124 const Pointer& pointer = pointerForId(id);
125 x += pointer.x;
126 y += pointer.y;
127 }
128 x /= count;
129 y /= count;
130 }
131 *outX = x;
132 *outY = y;
133}
134
135// --- CookedPointerData ---
136
137CookedPointerData::CookedPointerData() {
138 clear();
139}
140
141void CookedPointerData::clear() {
142 pointerCount = 0;
143 hoveringIdBits.clear();
144 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800145 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000146 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700147}
148
149void CookedPointerData::copyFrom(const CookedPointerData& other) {
150 pointerCount = other.pointerCount;
151 hoveringIdBits = other.hoveringIdBits;
152 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000153 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700154
155 for (uint32_t i = 0; i < pointerCount; i++) {
156 pointerProperties[i].copyFrom(other.pointerProperties[i]);
157 pointerCoords[i].copyFrom(other.pointerCoords[i]);
158
159 int id = pointerProperties[i].id;
160 idToIndex[id] = other.idToIndex[id];
161 }
162}
163
164// --- TouchInputMapper ---
165
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800166TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
167 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700168 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100169 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800170 mRawSurfaceWidth(-1),
171 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700172 mSurfaceLeft(0),
173 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700174 mSurfaceRight(0),
175 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700176 mPhysicalWidth(-1),
177 mPhysicalHeight(-1),
178 mPhysicalLeft(0),
179 mPhysicalTop(0),
180 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
181
182TouchInputMapper::~TouchInputMapper() {}
183
184uint32_t TouchInputMapper::getSources() {
185 return mSource;
186}
187
188void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
189 InputMapper::populateDeviceInfo(info);
190
Michael Wright227c5542020-07-02 18:30:52 +0100191 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 info->addMotionRange(mOrientedRanges.x);
193 info->addMotionRange(mOrientedRanges.y);
194 info->addMotionRange(mOrientedRanges.pressure);
195
Chris Yef74dc422020-09-02 22:41:50 -0700196 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700197 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
198 //
199 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
200 // motion, i.e. the hardware dimensions, as the finger could move completely across the
201 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700202 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
203 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
204 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
205 x.fuzz, x.resolution);
206 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
207 y.fuzz, y.resolution);
208 }
209
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700210 if (mOrientedRanges.haveSize) {
211 info->addMotionRange(mOrientedRanges.size);
212 }
213
214 if (mOrientedRanges.haveTouchSize) {
215 info->addMotionRange(mOrientedRanges.touchMajor);
216 info->addMotionRange(mOrientedRanges.touchMinor);
217 }
218
219 if (mOrientedRanges.haveToolSize) {
220 info->addMotionRange(mOrientedRanges.toolMajor);
221 info->addMotionRange(mOrientedRanges.toolMinor);
222 }
223
224 if (mOrientedRanges.haveOrientation) {
225 info->addMotionRange(mOrientedRanges.orientation);
226 }
227
228 if (mOrientedRanges.haveDistance) {
229 info->addMotionRange(mOrientedRanges.distance);
230 }
231
232 if (mOrientedRanges.haveTilt) {
233 info->addMotionRange(mOrientedRanges.tilt);
234 }
235
236 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
237 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
238 0.0f);
239 }
240 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
241 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
242 0.0f);
243 }
Michael Wright227c5542020-07-02 18:30:52 +0100244 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700245 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
246 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
247 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
248 x.fuzz, x.resolution);
249 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
250 y.fuzz, y.resolution);
251 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
252 x.fuzz, x.resolution);
253 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
254 y.fuzz, y.resolution);
255 }
256 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
257 }
258}
259
260void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700261 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
262 NamedEnum::string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700263 dumpParameters(dump);
264 dumpVirtualKeys(dump);
265 dumpRawPointerAxes(dump);
266 dumpCalibration(dump);
267 dumpAffineTransformation(dump);
268 dumpSurface(dump);
269
270 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
271 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
272 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
273 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
274 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
275 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
276 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
277 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
278 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
279 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
280 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
281 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
282 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
283 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
284 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
285 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
286 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
287
288 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
289 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
290 mLastRawState.rawPointerData.pointerCount);
291 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
292 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
293 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
294 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
295 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
296 "toolType=%d, isHovering=%s\n",
297 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
298 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
299 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
300 pointer.distance, pointer.toolType, toString(pointer.isHovering));
301 }
302
303 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
304 mLastCookedState.buttonState);
305 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
306 mLastCookedState.cookedPointerData.pointerCount);
307 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
308 const PointerProperties& pointerProperties =
309 mLastCookedState.cookedPointerData.pointerProperties[i];
310 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000311 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
312 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
313 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
315 "toolType=%d, isHovering=%s\n",
316 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
327 pointerProperties.toolType,
328 toString(mLastCookedState.cookedPointerData.isHovering(i)));
329 }
330
331 dump += INDENT3 "Stylus Fusion:\n";
332 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
333 toString(mExternalStylusConnected));
334 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
335 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
336 mExternalStylusFusionTimeout);
337 dump += INDENT3 "External Stylus State:\n";
338 dumpStylusState(dump, mExternalStylusState);
339
Michael Wright227c5542020-07-02 18:30:52 +0100340 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
342 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
343 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
344 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
345 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
346 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
347 }
348}
349
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
351 uint32_t changes) {
352 InputMapper::configure(when, config, changes);
353
354 mConfig = *config;
355
356 if (!changes) { // first time only
357 // Configure basic parameters.
358 configureParameters();
359
360 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mCursorScrollAccumulator.configure(getDeviceContext());
362 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700363
364 // Configure absolute axis information.
365 configureRawPointerAxes();
366
367 // Prepare input device calibration.
368 parseCalibration();
369 resolveCalibration();
370 }
371
372 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
373 // Update location calibration to reflect current settings
374 updateAffineTransformation();
375 }
376
377 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
378 // Update pointer speed.
379 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
380 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
381 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 }
383
384 bool resetNeeded = false;
385 if (!changes ||
386 (changes &
387 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800388 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
390 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
391 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
392 // Configure device sources, surface dimensions, orientation and
393 // scaling factors.
394 configureSurface(when, &resetNeeded);
395 }
396
397 if (changes && resetNeeded) {
398 // Send reset, unless this is the first time the device has been configured,
399 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +0000400 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
401 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 }
403}
404
405void TouchInputMapper::resolveExternalStylusPresence() {
406 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800407 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700408 mExternalStylusConnected = !devices.empty();
409
410 if (!mExternalStylusConnected) {
411 resetExternalStylus();
412 }
413}
414
415void TouchInputMapper::configureParameters() {
416 // Use the pointer presentation mode for devices that do not support distinct
417 // multitouch. The spot-based presentation relies on being able to accurately
418 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100420 ? Parameters::GestureMode::SINGLE_TOUCH
421 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422
423 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800424 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
425 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100427 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100429 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700430 } else if (gestureModeString != "default") {
431 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
432 }
433 }
434
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800435 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100437 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800438 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800441 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
442 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 // The device is a cursor device with a touch pad attached.
444 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100445 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446 } else {
447 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100448 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449 }
450
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800451 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452
453 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
455 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100461 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100463 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700464 } else if (deviceTypeString != "default") {
465 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
466 }
467 }
468
Michael Wright227c5542020-07-02 18:30:52 +0100469 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800470 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
471 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472
473 mParameters.hasAssociatedDisplay = false;
474 mParameters.associatedDisplayIsExternal = false;
475 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100476 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
477 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700478 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100479 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800480 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800482 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
483 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
485 }
486 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800487 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488 mParameters.hasAssociatedDisplay = true;
489 }
490
491 // Initial downs on external touch devices should wake the device.
492 // Normally we don't do this for internal touch screens to prevent them from waking
493 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 mParameters.wake = getDeviceContext().isExternal();
495 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496}
497
498void TouchInputMapper::dumpParameters(std::string& dump) {
499 dump += INDENT3 "Parameters:\n";
500
Chris Yea03dd232020-09-08 19:21:09 -0700501 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502
Chris Yea03dd232020-09-08 19:21:09 -0700503 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700504
505 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
506 "displayId='%s'\n",
507 toString(mParameters.hasAssociatedDisplay),
508 toString(mParameters.associatedDisplayIsExternal),
509 mParameters.uniqueDisplayId.c_str());
510 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
511}
512
513void TouchInputMapper::configureRawPointerAxes() {
514 mRawPointerAxes.clear();
515}
516
517void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
518 dump += INDENT3 "Raw Touch Axes:\n";
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
531 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
532}
533
534bool TouchInputMapper::hasExternalStylus() const {
535 return mExternalStylusConnected;
536}
537
538/**
539 * Determine which DisplayViewport to use.
540 * 1. If display port is specified, return the matching viewport. If matching viewport not
541 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800542 * 2. Always use the suggested viewport from WindowManagerService for pointers.
543 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700544 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800545 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700546 */
547std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800548 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800549 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700550 if (displayPort) {
551 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800552 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700553 }
554
Michael Wright227c5542020-07-02 18:30:52 +0100555 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800556 std::optional<DisplayViewport> viewport =
557 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
558 if (viewport) {
559 return viewport;
560 } else {
561 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
562 mConfig.defaultPointerDisplayId);
563 }
564 }
565
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 // Check if uniqueDisplayId is specified in idc file.
567 if (!mParameters.uniqueDisplayId.empty()) {
568 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
569 }
570
571 ViewportType viewportTypeToUse;
572 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100573 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700574 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100575 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700576 }
577
578 std::optional<DisplayViewport> viewport =
579 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100580 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700581 ALOGW("Input device %s should be associated with external display, "
582 "fallback to internal one for the external viewport is not found.",
583 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100584 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700585 }
586
587 return viewport;
588 }
589
590 // No associated display, return a non-display viewport.
591 DisplayViewport newViewport;
592 // Raw width and height in the natural orientation.
593 int32_t rawWidth = mRawPointerAxes.getRawWidth();
594 int32_t rawHeight = mRawPointerAxes.getRawHeight();
595 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
596 return std::make_optional(newViewport);
597}
598
599void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100600 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700601
602 resolveExternalStylusPresence();
603
604 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100605 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800606 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700607 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100608 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700609 if (hasStylus()) {
610 mSource |= AINPUT_SOURCE_STYLUS;
611 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800612 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700613 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100614 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700615 if (hasStylus()) {
616 mSource |= AINPUT_SOURCE_STYLUS;
617 }
618 if (hasExternalStylus()) {
619 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
620 }
Michael Wright227c5542020-07-02 18:30:52 +0100621 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700622 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100623 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700624 } else {
625 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100626 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700627 }
628
629 // Ensure we have valid X and Y axes.
630 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
631 ALOGW("Touch device '%s' did not report support for X or Y axis! "
632 "The device will be inoperable.",
633 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100634 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700635 return;
636 }
637
638 // Get associated display dimensions.
639 std::optional<DisplayViewport> newViewport = findViewport();
640 if (!newViewport) {
641 ALOGI("Touch device '%s' could not query the properties of its associated "
642 "display. The device will be inoperable until the display size "
643 "becomes available.",
644 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100645 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700646 return;
647 }
648
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000649 if (!newViewport->isActive) {
650 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
651 getDeviceName().c_str(), getDeviceId());
652 mDeviceMode = DeviceMode::DISABLED;
653 return;
654 }
655
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700656 // Raw width and height in the natural orientation.
657 int32_t rawWidth = mRawPointerAxes.getRawWidth();
658 int32_t rawHeight = mRawPointerAxes.getRawHeight();
659
660 bool viewportChanged = mViewport != *newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700661 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700662 if (viewportChanged) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700663 bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700664 mViewport = *newViewport;
665
Michael Wright227c5542020-07-02 18:30:52 +0100666 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700667 // Convert rotated viewport to natural surface coordinates.
668 int32_t naturalLogicalWidth, naturalLogicalHeight;
669 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
670 int32_t naturalPhysicalLeft, naturalPhysicalTop;
671 int32_t naturalDeviceWidth, naturalDeviceHeight;
672 switch (mViewport.orientation) {
673 case DISPLAY_ORIENTATION_90:
674 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
675 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
676 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
677 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800678 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700679 naturalPhysicalTop = mViewport.physicalLeft;
680 naturalDeviceWidth = mViewport.deviceHeight;
681 naturalDeviceHeight = mViewport.deviceWidth;
682 break;
683 case DISPLAY_ORIENTATION_180:
684 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
685 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
686 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
687 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
688 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
689 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
690 naturalDeviceWidth = mViewport.deviceWidth;
691 naturalDeviceHeight = mViewport.deviceHeight;
692 break;
693 case DISPLAY_ORIENTATION_270:
694 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
695 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
696 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
697 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
698 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800699 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700700 naturalDeviceWidth = mViewport.deviceHeight;
701 naturalDeviceHeight = mViewport.deviceWidth;
702 break;
703 case DISPLAY_ORIENTATION_0:
704 default:
705 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
706 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
707 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
708 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
709 naturalPhysicalLeft = mViewport.physicalLeft;
710 naturalPhysicalTop = mViewport.physicalTop;
711 naturalDeviceWidth = mViewport.deviceWidth;
712 naturalDeviceHeight = mViewport.deviceHeight;
713 break;
714 }
715
716 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
717 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
718 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
719 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
720 }
721
722 mPhysicalWidth = naturalPhysicalWidth;
723 mPhysicalHeight = naturalPhysicalHeight;
724 mPhysicalLeft = naturalPhysicalLeft;
725 mPhysicalTop = naturalPhysicalTop;
726
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700727 const int32_t oldSurfaceWidth = mRawSurfaceWidth;
728 const int32_t oldSurfaceHeight = mRawSurfaceHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800729 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
730 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700731 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
732 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800733 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
734 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700735
Prabir Pradhand7482e72021-03-09 13:54:55 -0800736 if (isPerWindowInputRotationEnabled()) {
737 // When per-window input rotation is enabled, InputReader works in the un-rotated
738 // coordinate space, so we don't need to do anything if the device is already
739 // orientation-aware. If the device is not orientation-aware, then we need to apply
740 // the inverse rotation of the display so that when the display rotation is applied
741 // later as a part of the per-window transform, we get the expected screen
742 // coordinates.
743 mSurfaceOrientation = mParameters.orientationAware
744 ? DISPLAY_ORIENTATION_0
745 : getInverseRotation(mViewport.orientation);
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700746 // For orientation-aware devices that work in the un-rotated coordinate space, the
747 // viewport update should be skipped if it is only a change in the orientation.
748 skipViewportUpdate = mParameters.orientationAware &&
749 mRawSurfaceWidth == oldSurfaceWidth &&
750 mRawSurfaceHeight == oldSurfaceHeight && viewportOrientationChanged;
Prabir Pradhand7482e72021-03-09 13:54:55 -0800751 } else {
752 mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation
753 : DISPLAY_ORIENTATION_0;
754 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700755 } else {
756 mPhysicalWidth = rawWidth;
757 mPhysicalHeight = rawHeight;
758 mPhysicalLeft = 0;
759 mPhysicalTop = 0;
760
Arthur Hung4197f6b2020-03-16 15:39:59 +0800761 mRawSurfaceWidth = rawWidth;
762 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700763 mSurfaceLeft = 0;
764 mSurfaceTop = 0;
765 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
766 }
767 }
768
769 // If moving between pointer modes, need to reset some state.
770 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
771 if (deviceModeChanged) {
772 mOrientedRanges.clear();
773 }
774
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800775 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
776 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100777 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800778 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
779 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800780 if (mPointerController == nullptr) {
781 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700782 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800783 if (mConfig.pointerCapture) {
784 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
785 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700786 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100787 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700788 }
789
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700790 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700791 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
792 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800793 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700794 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
795
796 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800797 mXScale = float(mRawSurfaceWidth) / rawWidth;
798 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700799 mXTranslate = -mSurfaceLeft;
800 mYTranslate = -mSurfaceTop;
801 mXPrecision = 1.0f / mXScale;
802 mYPrecision = 1.0f / mYScale;
803
804 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
805 mOrientedRanges.x.source = mSource;
806 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
807 mOrientedRanges.y.source = mSource;
808
809 configureVirtualKeys();
810
811 // Scale factor for terms that are not oriented in a particular axis.
812 // If the pixels are square then xScale == yScale otherwise we fake it
813 // by choosing an average.
814 mGeometricScale = avg(mXScale, mYScale);
815
816 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800817 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700818
819 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100820 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700821 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
822 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
823 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
824 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
825 } else {
826 mSizeScale = 0.0f;
827 }
828
829 mOrientedRanges.haveTouchSize = true;
830 mOrientedRanges.haveToolSize = true;
831 mOrientedRanges.haveSize = true;
832
833 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
834 mOrientedRanges.touchMajor.source = mSource;
835 mOrientedRanges.touchMajor.min = 0;
836 mOrientedRanges.touchMajor.max = diagonalSize;
837 mOrientedRanges.touchMajor.flat = 0;
838 mOrientedRanges.touchMajor.fuzz = 0;
839 mOrientedRanges.touchMajor.resolution = 0;
840
841 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
842 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
843
844 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
845 mOrientedRanges.toolMajor.source = mSource;
846 mOrientedRanges.toolMajor.min = 0;
847 mOrientedRanges.toolMajor.max = diagonalSize;
848 mOrientedRanges.toolMajor.flat = 0;
849 mOrientedRanges.toolMajor.fuzz = 0;
850 mOrientedRanges.toolMajor.resolution = 0;
851
852 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
853 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
854
855 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
856 mOrientedRanges.size.source = mSource;
857 mOrientedRanges.size.min = 0;
858 mOrientedRanges.size.max = 1.0;
859 mOrientedRanges.size.flat = 0;
860 mOrientedRanges.size.fuzz = 0;
861 mOrientedRanges.size.resolution = 0;
862 } else {
863 mSizeScale = 0.0f;
864 }
865
866 // Pressure factors.
867 mPressureScale = 0;
868 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100869 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
870 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700871 if (mCalibration.havePressureScale) {
872 mPressureScale = mCalibration.pressureScale;
873 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
874 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
875 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
876 }
877 }
878
879 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
880 mOrientedRanges.pressure.source = mSource;
881 mOrientedRanges.pressure.min = 0;
882 mOrientedRanges.pressure.max = pressureMax;
883 mOrientedRanges.pressure.flat = 0;
884 mOrientedRanges.pressure.fuzz = 0;
885 mOrientedRanges.pressure.resolution = 0;
886
887 // Tilt
888 mTiltXCenter = 0;
889 mTiltXScale = 0;
890 mTiltYCenter = 0;
891 mTiltYScale = 0;
892 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
893 if (mHaveTilt) {
894 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
895 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
896 mTiltXScale = M_PI / 180;
897 mTiltYScale = M_PI / 180;
898
899 mOrientedRanges.haveTilt = true;
900
901 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
902 mOrientedRanges.tilt.source = mSource;
903 mOrientedRanges.tilt.min = 0;
904 mOrientedRanges.tilt.max = M_PI_2;
905 mOrientedRanges.tilt.flat = 0;
906 mOrientedRanges.tilt.fuzz = 0;
907 mOrientedRanges.tilt.resolution = 0;
908 }
909
910 // Orientation
911 mOrientationScale = 0;
912 if (mHaveTilt) {
913 mOrientedRanges.haveOrientation = true;
914
915 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
916 mOrientedRanges.orientation.source = mSource;
917 mOrientedRanges.orientation.min = -M_PI;
918 mOrientedRanges.orientation.max = M_PI;
919 mOrientedRanges.orientation.flat = 0;
920 mOrientedRanges.orientation.fuzz = 0;
921 mOrientedRanges.orientation.resolution = 0;
922 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100923 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700924 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100925 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700926 if (mRawPointerAxes.orientation.valid) {
927 if (mRawPointerAxes.orientation.maxValue > 0) {
928 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
929 } else if (mRawPointerAxes.orientation.minValue < 0) {
930 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
931 } else {
932 mOrientationScale = 0;
933 }
934 }
935 }
936
937 mOrientedRanges.haveOrientation = true;
938
939 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
940 mOrientedRanges.orientation.source = mSource;
941 mOrientedRanges.orientation.min = -M_PI_2;
942 mOrientedRanges.orientation.max = M_PI_2;
943 mOrientedRanges.orientation.flat = 0;
944 mOrientedRanges.orientation.fuzz = 0;
945 mOrientedRanges.orientation.resolution = 0;
946 }
947
948 // Distance
949 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100950 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
951 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700952 if (mCalibration.haveDistanceScale) {
953 mDistanceScale = mCalibration.distanceScale;
954 } else {
955 mDistanceScale = 1.0f;
956 }
957 }
958
959 mOrientedRanges.haveDistance = true;
960
961 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
962 mOrientedRanges.distance.source = mSource;
963 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
964 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
965 mOrientedRanges.distance.flat = 0;
966 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
967 mOrientedRanges.distance.resolution = 0;
968 }
969
970 // Compute oriented precision, scales and ranges.
971 // Note that the maximum value reported is an inclusive maximum value so it is one
972 // unit less than the total width or height of surface.
973 switch (mSurfaceOrientation) {
974 case DISPLAY_ORIENTATION_90:
975 case DISPLAY_ORIENTATION_270:
976 mOrientedXPrecision = mYPrecision;
977 mOrientedYPrecision = mXPrecision;
978
979 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800980 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700981 mOrientedRanges.x.flat = 0;
982 mOrientedRanges.x.fuzz = 0;
983 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
984
985 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800986 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700987 mOrientedRanges.y.flat = 0;
988 mOrientedRanges.y.fuzz = 0;
989 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
990 break;
991
992 default:
993 mOrientedXPrecision = mXPrecision;
994 mOrientedYPrecision = mYPrecision;
995
996 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800997 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700998 mOrientedRanges.x.flat = 0;
999 mOrientedRanges.x.fuzz = 0;
1000 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1001
1002 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001003 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004 mOrientedRanges.y.flat = 0;
1005 mOrientedRanges.y.fuzz = 0;
1006 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1007 break;
1008 }
1009
1010 // Location
1011 updateAffineTransformation();
1012
Michael Wright227c5542020-07-02 18:30:52 +01001013 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001014 // Compute pointer gesture detection parameters.
1015 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001016 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001017
1018 // Scale movements such that one whole swipe of the touch pad covers a
1019 // given area relative to the diagonal size of the display when no acceleration
1020 // is applied.
1021 // Assume that the touch pad has a square aspect ratio such that movements in
1022 // X and Y of the same number of raw units cover the same physical distance.
1023 mPointerXMovementScale =
1024 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1025 mPointerYMovementScale = mPointerXMovementScale;
1026
1027 // Scale zooms to cover a smaller range of the display than movements do.
1028 // This value determines the area around the pointer that is affected by freeform
1029 // pointer gestures.
1030 mPointerXZoomScale =
1031 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1032 mPointerYZoomScale = mPointerXZoomScale;
1033
1034 // Max width between pointers to detect a swipe gesture is more than some fraction
1035 // of the diagonal axis of the touch pad. Touches that are wider than this are
1036 // translated into freeform gestures.
1037 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1038
1039 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001040 const nsecs_t readTime = when; // synthetic event
1041 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001042 }
1043
1044 // Inform the dispatcher about the changes.
1045 *outResetNeeded = true;
1046 bumpGeneration();
1047 }
1048}
1049
1050void TouchInputMapper::dumpSurface(std::string& dump) {
1051 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001052 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1053 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001054 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1055 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001056 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1057 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001058 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1059 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1060 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1061 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1062 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1063}
1064
1065void TouchInputMapper::configureVirtualKeys() {
1066 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001067 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001068
1069 mVirtualKeys.clear();
1070
1071 if (virtualKeyDefinitions.size() == 0) {
1072 return;
1073 }
1074
1075 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1076 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1077 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1078 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1079
1080 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1081 VirtualKey virtualKey;
1082
1083 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1084 int32_t keyCode;
1085 int32_t dummyKeyMetaState;
1086 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001087 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1088 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001089 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1090 continue; // drop the key
1091 }
1092
1093 virtualKey.keyCode = keyCode;
1094 virtualKey.flags = flags;
1095
1096 // convert the key definition's display coordinates into touch coordinates for a hit box
1097 int32_t halfWidth = virtualKeyDefinition.width / 2;
1098 int32_t halfHeight = virtualKeyDefinition.height / 2;
1099
1100 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001101 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001102 touchScreenLeft;
1103 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001104 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001106 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1107 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001108 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001109 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1110 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111 touchScreenTop;
1112 mVirtualKeys.push_back(virtualKey);
1113 }
1114}
1115
1116void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1117 if (!mVirtualKeys.empty()) {
1118 dump += INDENT3 "Virtual Keys:\n";
1119
1120 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1121 const VirtualKey& virtualKey = mVirtualKeys[i];
1122 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1123 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1124 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1125 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1126 }
1127 }
1128}
1129
1130void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001131 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132 Calibration& out = mCalibration;
1133
1134 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001135 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 String8 sizeCalibrationString;
1137 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1138 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001139 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001140 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001141 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001145 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001147 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (sizeCalibrationString != "default") {
1149 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1150 }
1151 }
1152
1153 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1154 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1155 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1156
1157 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001158 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 String8 pressureCalibrationString;
1160 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1161 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001163 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001164 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 } else if (pressureCalibrationString != "default") {
1168 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1169 pressureCalibrationString.string());
1170 }
1171 }
1172
1173 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1174
1175 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001176 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 String8 orientationCalibrationString;
1178 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1179 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001180 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001182 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001185 } else if (orientationCalibrationString != "default") {
1186 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1187 orientationCalibrationString.string());
1188 }
1189 }
1190
1191 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 String8 distanceCalibrationString;
1194 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1195 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001198 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 } else if (distanceCalibrationString != "default") {
1200 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1201 distanceCalibrationString.string());
1202 }
1203 }
1204
1205 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1206
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 String8 coverageCalibrationString;
1209 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1210 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 } else if (coverageCalibrationString != "default") {
1215 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1216 coverageCalibrationString.string());
1217 }
1218 }
1219}
1220
1221void TouchInputMapper::resolveCalibration() {
1222 // Size
1223 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001224 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1225 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226 }
1227 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001228 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230
1231 // Pressure
1232 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001233 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1234 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235 }
1236 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001237 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 }
1239
1240 // Orientation
1241 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001242 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1243 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 }
1245 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001246 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 }
1248
1249 // Distance
1250 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001251 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1252 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 }
1254 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001255 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256 }
1257
1258 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001259 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1260 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 }
1262}
1263
1264void TouchInputMapper::dumpCalibration(std::string& dump) {
1265 dump += INDENT3 "Calibration:\n";
1266
1267 // Size
1268 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001269 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270 dump += INDENT4 "touch.size.calibration: none\n";
1271 break;
Michael Wright227c5542020-07-02 18:30:52 +01001272 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 dump += INDENT4 "touch.size.calibration: geometric\n";
1274 break;
Michael Wright227c5542020-07-02 18:30:52 +01001275 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 dump += INDENT4 "touch.size.calibration: diameter\n";
1277 break;
Michael Wright227c5542020-07-02 18:30:52 +01001278 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 dump += INDENT4 "touch.size.calibration: box\n";
1280 break;
Michael Wright227c5542020-07-02 18:30:52 +01001281 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 dump += INDENT4 "touch.size.calibration: area\n";
1283 break;
1284 default:
1285 ALOG_ASSERT(false);
1286 }
1287
1288 if (mCalibration.haveSizeScale) {
1289 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1290 }
1291
1292 if (mCalibration.haveSizeBias) {
1293 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1294 }
1295
1296 if (mCalibration.haveSizeIsSummed) {
1297 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1298 toString(mCalibration.sizeIsSummed));
1299 }
1300
1301 // Pressure
1302 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001303 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += INDENT4 "touch.pressure.calibration: none\n";
1305 break;
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.pressure.calibration: physical\n";
1308 break;
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1311 break;
1312 default:
1313 ALOG_ASSERT(false);
1314 }
1315
1316 if (mCalibration.havePressureScale) {
1317 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1318 }
1319
1320 // Orientation
1321 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001322 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001323 dump += INDENT4 "touch.orientation.calibration: none\n";
1324 break;
Michael Wright227c5542020-07-02 18:30:52 +01001325 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1327 break;
Michael Wright227c5542020-07-02 18:30:52 +01001328 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 dump += INDENT4 "touch.orientation.calibration: vector\n";
1330 break;
1331 default:
1332 ALOG_ASSERT(false);
1333 }
1334
1335 // Distance
1336 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001337 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 dump += INDENT4 "touch.distance.calibration: none\n";
1339 break;
Michael Wright227c5542020-07-02 18:30:52 +01001340 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.distance.calibration: scaled\n";
1342 break;
1343 default:
1344 ALOG_ASSERT(false);
1345 }
1346
1347 if (mCalibration.haveDistanceScale) {
1348 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1349 }
1350
1351 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001352 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 dump += INDENT4 "touch.coverage.calibration: none\n";
1354 break;
Michael Wright227c5542020-07-02 18:30:52 +01001355 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356 dump += INDENT4 "touch.coverage.calibration: box\n";
1357 break;
1358 default:
1359 ALOG_ASSERT(false);
1360 }
1361}
1362
1363void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1364 dump += INDENT3 "Affine Transformation:\n";
1365
1366 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1367 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1368 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1369 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1370 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1371 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1372}
1373
1374void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001375 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001376 mSurfaceOrientation);
1377}
1378
1379void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001380 mCursorButtonAccumulator.reset(getDeviceContext());
1381 mCursorScrollAccumulator.reset(getDeviceContext());
1382 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001383
1384 mPointerVelocityControl.reset();
1385 mWheelXVelocityControl.reset();
1386 mWheelYVelocityControl.reset();
1387
1388 mRawStatesPending.clear();
1389 mCurrentRawState.clear();
1390 mCurrentCookedState.clear();
1391 mLastRawState.clear();
1392 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001393 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001394 mSentHoverEnter = false;
1395 mHavePointerIds = false;
1396 mCurrentMotionAborted = false;
1397 mDownTime = 0;
1398
1399 mCurrentVirtualKey.down = false;
1400
1401 mPointerGesture.reset();
1402 mPointerSimple.reset();
1403 resetExternalStylus();
1404
1405 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001406 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407 mPointerController->clearSpots();
1408 }
1409
1410 InputMapper::reset(when);
1411}
1412
1413void TouchInputMapper::resetExternalStylus() {
1414 mExternalStylusState.clear();
1415 mExternalStylusId = -1;
1416 mExternalStylusFusionTimeout = LLONG_MAX;
1417 mExternalStylusDataPending = false;
1418}
1419
1420void TouchInputMapper::clearStylusDataPendingFlags() {
1421 mExternalStylusDataPending = false;
1422 mExternalStylusFusionTimeout = LLONG_MAX;
1423}
1424
1425void TouchInputMapper::process(const RawEvent* rawEvent) {
1426 mCursorButtonAccumulator.process(rawEvent);
1427 mCursorScrollAccumulator.process(rawEvent);
1428 mTouchButtonAccumulator.process(rawEvent);
1429
1430 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001431 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001432 }
1433}
1434
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001435void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436 // Push a new state.
1437 mRawStatesPending.emplace_back();
1438
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001439 RawState& next = mRawStatesPending.back();
1440 next.clear();
1441 next.when = when;
1442 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001443
1444 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001445 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1447
1448 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001449 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1450 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451 mCursorScrollAccumulator.finishSync();
1452
1453 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001454 syncTouch(when, &next);
1455
1456 // The last RawState is the actually second to last, since we just added a new state
1457 const RawState& last =
1458 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001459
1460 // Assign pointer ids.
1461 if (!mHavePointerIds) {
1462 assignPointerIds(last, next);
1463 }
1464
1465#if DEBUG_RAW_EVENTS
1466 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001467 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001468 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1469 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1470 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1471 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001472#endif
1473
1474 processRawTouches(false /*timeout*/);
1475}
1476
1477void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001478 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001480 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001481 mCurrentCookedState.clear();
1482 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001483 return;
1484 }
1485
1486 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1487 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1488 // touching the current state will only observe the events that have been dispatched to the
1489 // rest of the pipeline.
1490 const size_t N = mRawStatesPending.size();
1491 size_t count;
1492 for (count = 0; count < N; count++) {
1493 const RawState& next = mRawStatesPending[count];
1494
1495 // A failure to assign the stylus id means that we're waiting on stylus data
1496 // and so should defer the rest of the pipeline.
1497 if (assignExternalStylusId(next, timeout)) {
1498 break;
1499 }
1500
1501 // All ready to go.
1502 clearStylusDataPendingFlags();
1503 mCurrentRawState.copyFrom(next);
1504 if (mCurrentRawState.when < mLastRawState.when) {
1505 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001506 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001507 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001508 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001509 }
1510 if (count != 0) {
1511 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1512 }
1513
1514 if (mExternalStylusDataPending) {
1515 if (timeout) {
1516 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1517 clearStylusDataPendingFlags();
1518 mCurrentRawState.copyFrom(mLastRawState);
1519#if DEBUG_STYLUS_FUSION
1520 ALOGD("Timeout expired, synthesizing event with new stylus data");
1521#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001522 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1523 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1525 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1526 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1527 }
1528 }
1529}
1530
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001531void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001532 // Always start with a clean state.
1533 mCurrentCookedState.clear();
1534
1535 // Apply stylus buttons to current raw state.
1536 applyExternalStylusButtonState(when);
1537
1538 // Handle policy on initial down or hover events.
1539 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1540 mCurrentRawState.rawPointerData.pointerCount != 0;
1541
1542 uint32_t policyFlags = 0;
1543 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1544 if (initialDown || buttonsPressed) {
1545 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001546 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001547 getContext()->fadePointer();
1548 }
1549
1550 if (mParameters.wake) {
1551 policyFlags |= POLICY_FLAG_WAKE;
1552 }
1553 }
1554
1555 // Consume raw off-screen touches before cooking pointer data.
1556 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001557 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001558 mCurrentRawState.rawPointerData.clear();
1559 }
1560
1561 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1562 // with cooked pointer data that has the same ids and indices as the raw data.
1563 // The following code can use either the raw or cooked data, as needed.
1564 cookPointerData();
1565
1566 // Apply stylus pressure to current cooked state.
1567 applyExternalStylusTouchState(when);
1568
1569 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001570 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1571 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001572 mCurrentCookedState.buttonState);
1573
1574 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001575 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1577 uint32_t id = idBits.clearFirstMarkedBit();
1578 const RawPointerData::Pointer& pointer =
1579 mCurrentRawState.rawPointerData.pointerForId(id);
1580 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1581 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1582 mCurrentCookedState.stylusIdBits.markBit(id);
1583 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1584 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1585 mCurrentCookedState.fingerIdBits.markBit(id);
1586 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1587 mCurrentCookedState.mouseIdBits.markBit(id);
1588 }
1589 }
1590 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1591 uint32_t id = idBits.clearFirstMarkedBit();
1592 const RawPointerData::Pointer& pointer =
1593 mCurrentRawState.rawPointerData.pointerForId(id);
1594 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1595 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1596 mCurrentCookedState.stylusIdBits.markBit(id);
1597 }
1598 }
1599
1600 // Stylus takes precedence over all tools, then mouse, then finger.
1601 PointerUsage pointerUsage = mPointerUsage;
1602 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1603 mCurrentCookedState.mouseIdBits.clear();
1604 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001605 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1607 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001608 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001609 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1610 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001611 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001612 }
1613
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001614 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001616 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617
1618 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001619 dispatchButtonRelease(when, readTime, policyFlags);
1620 dispatchHoverExit(when, readTime, policyFlags);
1621 dispatchTouches(when, readTime, policyFlags);
1622 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1623 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 }
1625
1626 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1627 mCurrentMotionAborted = false;
1628 }
1629 }
1630
1631 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001632 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001633 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1634 mCurrentCookedState.buttonState);
1635
1636 // Clear some transient state.
1637 mCurrentRawState.rawVScroll = 0;
1638 mCurrentRawState.rawHScroll = 0;
1639
1640 // Copy current touch to last touch in preparation for the next cycle.
1641 mLastRawState.copyFrom(mCurrentRawState);
1642 mLastCookedState.copyFrom(mCurrentCookedState);
1643}
1644
Garfield Tanc734e4f2021-01-15 20:01:39 -08001645void TouchInputMapper::updateTouchSpots() {
1646 if (!mConfig.showTouches || mPointerController == nullptr) {
1647 return;
1648 }
1649
1650 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1651 // clear touch spots.
1652 if (mDeviceMode != DeviceMode::DIRECT &&
1653 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1654 return;
1655 }
1656
1657 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1658 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1659
1660 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001661 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1662 mCurrentCookedState.cookedPointerData.idToIndex,
1663 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001664}
1665
1666bool TouchInputMapper::isTouchScreen() {
1667 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1668 mParameters.hasAssociatedDisplay;
1669}
1670
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001671void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001672 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001673 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1674 }
1675}
1676
1677void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1678 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1679 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1680
1681 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1682 float pressure = mExternalStylusState.pressure;
1683 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1684 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1685 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1686 }
1687 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1688 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1689
1690 PointerProperties& properties =
1691 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1692 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1693 properties.toolType = mExternalStylusState.toolType;
1694 }
1695 }
1696}
1697
1698bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001699 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001700 return false;
1701 }
1702
1703 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1704 state.rawPointerData.pointerCount != 0;
1705 if (initialDown) {
1706 if (mExternalStylusState.pressure != 0.0f) {
1707#if DEBUG_STYLUS_FUSION
1708 ALOGD("Have both stylus and touch data, beginning fusion");
1709#endif
1710 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1711 } else if (timeout) {
1712#if DEBUG_STYLUS_FUSION
1713 ALOGD("Timeout expired, assuming touch is not a stylus.");
1714#endif
1715 resetExternalStylus();
1716 } else {
1717 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1718 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1719 }
1720#if DEBUG_STYLUS_FUSION
1721 ALOGD("No stylus data but stylus is connected, requesting timeout "
1722 "(%" PRId64 "ms)",
1723 mExternalStylusFusionTimeout);
1724#endif
1725 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1726 return true;
1727 }
1728 }
1729
1730 // Check if the stylus pointer has gone up.
1731 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1732#if DEBUG_STYLUS_FUSION
1733 ALOGD("Stylus pointer is going up");
1734#endif
1735 mExternalStylusId = -1;
1736 }
1737
1738 return false;
1739}
1740
1741void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001742 if (mDeviceMode == DeviceMode::POINTER) {
1743 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001744 // Since this is a synthetic event, we can consider its latency to be zero
1745 const nsecs_t readTime = when;
1746 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001747 }
Michael Wright227c5542020-07-02 18:30:52 +01001748 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001749 if (mExternalStylusFusionTimeout < when) {
1750 processRawTouches(true /*timeout*/);
1751 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1752 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1753 }
1754 }
1755}
1756
1757void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1758 mExternalStylusState.copyFrom(state);
1759 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1760 // We're either in the middle of a fused stream of data or we're waiting on data before
1761 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1762 // data.
1763 mExternalStylusDataPending = true;
1764 processRawTouches(false /*timeout*/);
1765 }
1766}
1767
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001768bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001769 // Check for release of a virtual key.
1770 if (mCurrentVirtualKey.down) {
1771 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1772 // Pointer went up while virtual key was down.
1773 mCurrentVirtualKey.down = false;
1774 if (!mCurrentVirtualKey.ignored) {
1775#if DEBUG_VIRTUAL_KEYS
1776 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1777 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1778#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001779 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1781 }
1782 return true;
1783 }
1784
1785 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1786 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1787 const RawPointerData::Pointer& pointer =
1788 mCurrentRawState.rawPointerData.pointerForId(id);
1789 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1790 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1791 // Pointer is still within the space of the virtual key.
1792 return true;
1793 }
1794 }
1795
1796 // Pointer left virtual key area or another pointer also went down.
1797 // Send key cancellation but do not consume the touch yet.
1798 // This is useful when the user swipes through from the virtual key area
1799 // into the main display surface.
1800 mCurrentVirtualKey.down = false;
1801 if (!mCurrentVirtualKey.ignored) {
1802#if DEBUG_VIRTUAL_KEYS
1803 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1804 mCurrentVirtualKey.scanCode);
1805#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001806 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001807 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1808 AKEY_EVENT_FLAG_CANCELED);
1809 }
1810 }
1811
1812 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1813 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1814 // Pointer just went down. Check for virtual key press or off-screen touches.
1815 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1816 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001817 // Exclude unscaled device for inside surface checking.
1818 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001819 // If exactly one pointer went down, check for virtual key hit.
1820 // Otherwise we will drop the entire stroke.
1821 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1822 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1823 if (virtualKey) {
1824 mCurrentVirtualKey.down = true;
1825 mCurrentVirtualKey.downTime = when;
1826 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1827 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1828 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001829 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1830 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001831
1832 if (!mCurrentVirtualKey.ignored) {
1833#if DEBUG_VIRTUAL_KEYS
1834 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1835 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1836#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001837 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001838 AKEY_EVENT_FLAG_FROM_SYSTEM |
1839 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1840 }
1841 }
1842 }
1843 return true;
1844 }
1845 }
1846
1847 // Disable all virtual key touches that happen within a short time interval of the
1848 // most recent touch within the screen area. The idea is to filter out stray
1849 // virtual key presses when interacting with the touch screen.
1850 //
1851 // Problems we're trying to solve:
1852 //
1853 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1854 // virtual key area that is implemented by a separate touch panel and accidentally
1855 // triggers a virtual key.
1856 //
1857 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1858 // area and accidentally triggers a virtual key. This often happens when virtual keys
1859 // are layed out below the screen near to where the on screen keyboard's space bar
1860 // is displayed.
1861 if (mConfig.virtualKeyQuietTime > 0 &&
1862 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001863 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001864 }
1865 return false;
1866}
1867
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001868void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001869 int32_t keyEventAction, int32_t keyEventFlags) {
1870 int32_t keyCode = mCurrentVirtualKey.keyCode;
1871 int32_t scanCode = mCurrentVirtualKey.scanCode;
1872 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001873 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001874 policyFlags |= POLICY_FLAG_VIRTUAL;
1875
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001876 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1877 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1878 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001879 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001880}
1881
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001882void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001883 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1884 if (!currentIdBits.isEmpty()) {
1885 int32_t metaState = getContext()->getGlobalMetaState();
1886 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001887 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1888 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001889 mCurrentCookedState.cookedPointerData.pointerProperties,
1890 mCurrentCookedState.cookedPointerData.pointerCoords,
1891 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1892 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1893 mCurrentMotionAborted = true;
1894 }
1895}
1896
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001897void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001898 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1899 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1900 int32_t metaState = getContext()->getGlobalMetaState();
1901 int32_t buttonState = mCurrentCookedState.buttonState;
1902
1903 if (currentIdBits == lastIdBits) {
1904 if (!currentIdBits.isEmpty()) {
1905 // No pointer id changes so this is a move event.
1906 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001907 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1908 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001909 mCurrentCookedState.cookedPointerData.pointerProperties,
1910 mCurrentCookedState.cookedPointerData.pointerCoords,
1911 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1912 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1913 }
1914 } else {
1915 // There may be pointers going up and pointers going down and pointers moving
1916 // all at the same time.
1917 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1918 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1919 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1920 BitSet32 dispatchedIdBits(lastIdBits.value);
1921
1922 // Update last coordinates of pointers that have moved so that we observe the new
1923 // pointer positions at the same time as other pointers that have just gone up.
1924 bool moveNeeded =
1925 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1926 mCurrentCookedState.cookedPointerData.pointerCoords,
1927 mCurrentCookedState.cookedPointerData.idToIndex,
1928 mLastCookedState.cookedPointerData.pointerProperties,
1929 mLastCookedState.cookedPointerData.pointerCoords,
1930 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1931 if (buttonState != mLastCookedState.buttonState) {
1932 moveNeeded = true;
1933 }
1934
1935 // Dispatch pointer up events.
1936 while (!upIdBits.isEmpty()) {
1937 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001938 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001939 if (isCanceled) {
1940 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1941 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001942 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001943 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001944 mLastCookedState.cookedPointerData.pointerProperties,
1945 mLastCookedState.cookedPointerData.pointerCoords,
1946 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1947 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1948 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001949 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001950 }
1951
1952 // Dispatch move events if any of the remaining pointers moved from their old locations.
1953 // Although applications receive new locations as part of individual pointer up
1954 // events, they do not generally handle them except when presented in a move event.
1955 if (moveNeeded && !moveIdBits.isEmpty()) {
1956 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001957 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1958 metaState, buttonState, 0,
1959 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001960 mCurrentCookedState.cookedPointerData.pointerCoords,
1961 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1962 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1963 }
1964
1965 // Dispatch pointer down events using the new pointer locations.
1966 while (!downIdBits.isEmpty()) {
1967 uint32_t downId = downIdBits.clearFirstMarkedBit();
1968 dispatchedIdBits.markBit(downId);
1969
1970 if (dispatchedIdBits.count() == 1) {
1971 // First pointer is going down. Set down time.
1972 mDownTime = when;
1973 }
1974
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001975 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
1976 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001977 mCurrentCookedState.cookedPointerData.pointerProperties,
1978 mCurrentCookedState.cookedPointerData.pointerCoords,
1979 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1980 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1981 }
1982 }
1983}
1984
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001985void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001986 if (mSentHoverEnter &&
1987 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1988 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1989 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001990 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
1991 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001992 mLastCookedState.cookedPointerData.pointerProperties,
1993 mLastCookedState.cookedPointerData.pointerCoords,
1994 mLastCookedState.cookedPointerData.idToIndex,
1995 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1996 mOrientedYPrecision, mDownTime);
1997 mSentHoverEnter = false;
1998 }
1999}
2000
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002001void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2002 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002003 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2004 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2005 int32_t metaState = getContext()->getGlobalMetaState();
2006 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002007 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2008 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002009 mCurrentCookedState.cookedPointerData.pointerProperties,
2010 mCurrentCookedState.cookedPointerData.pointerCoords,
2011 mCurrentCookedState.cookedPointerData.idToIndex,
2012 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2013 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2014 mSentHoverEnter = true;
2015 }
2016
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002017 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2018 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002019 mCurrentCookedState.cookedPointerData.pointerProperties,
2020 mCurrentCookedState.cookedPointerData.pointerCoords,
2021 mCurrentCookedState.cookedPointerData.idToIndex,
2022 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2023 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2024 }
2025}
2026
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002027void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002028 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2029 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2030 const int32_t metaState = getContext()->getGlobalMetaState();
2031 int32_t buttonState = mLastCookedState.buttonState;
2032 while (!releasedButtons.isEmpty()) {
2033 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2034 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002035 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002036 actionButton, 0, metaState, buttonState, 0,
2037 mCurrentCookedState.cookedPointerData.pointerProperties,
2038 mCurrentCookedState.cookedPointerData.pointerCoords,
2039 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2040 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2041 }
2042}
2043
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002044void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002045 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2046 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2047 const int32_t metaState = getContext()->getGlobalMetaState();
2048 int32_t buttonState = mLastCookedState.buttonState;
2049 while (!pressedButtons.isEmpty()) {
2050 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2051 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002052 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2053 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002054 mCurrentCookedState.cookedPointerData.pointerProperties,
2055 mCurrentCookedState.cookedPointerData.pointerCoords,
2056 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2057 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2058 }
2059}
2060
2061const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2062 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2063 return cookedPointerData.touchingIdBits;
2064 }
2065 return cookedPointerData.hoveringIdBits;
2066}
2067
2068void TouchInputMapper::cookPointerData() {
2069 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2070
2071 mCurrentCookedState.cookedPointerData.clear();
2072 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2073 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2074 mCurrentRawState.rawPointerData.hoveringIdBits;
2075 mCurrentCookedState.cookedPointerData.touchingIdBits =
2076 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002077 mCurrentCookedState.cookedPointerData.canceledIdBits =
2078 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002079
2080 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2081 mCurrentCookedState.buttonState = 0;
2082 } else {
2083 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2084 }
2085
2086 // Walk through the the active pointers and map device coordinates onto
2087 // surface coordinates and adjust for display orientation.
2088 for (uint32_t i = 0; i < currentPointerCount; i++) {
2089 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2090
2091 // Size
2092 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2093 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002094 case Calibration::SizeCalibration::GEOMETRIC:
2095 case Calibration::SizeCalibration::DIAMETER:
2096 case Calibration::SizeCalibration::BOX:
2097 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002098 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2099 touchMajor = in.touchMajor;
2100 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2101 toolMajor = in.toolMajor;
2102 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2103 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2104 : in.touchMajor;
2105 } else if (mRawPointerAxes.touchMajor.valid) {
2106 toolMajor = touchMajor = in.touchMajor;
2107 toolMinor = touchMinor =
2108 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2109 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2110 : in.touchMajor;
2111 } else if (mRawPointerAxes.toolMajor.valid) {
2112 touchMajor = toolMajor = in.toolMajor;
2113 touchMinor = toolMinor =
2114 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2115 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2116 : in.toolMajor;
2117 } else {
2118 ALOG_ASSERT(false,
2119 "No touch or tool axes. "
2120 "Size calibration should have been resolved to NONE.");
2121 touchMajor = 0;
2122 touchMinor = 0;
2123 toolMajor = 0;
2124 toolMinor = 0;
2125 size = 0;
2126 }
2127
2128 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2129 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2130 if (touchingCount > 1) {
2131 touchMajor /= touchingCount;
2132 touchMinor /= touchingCount;
2133 toolMajor /= touchingCount;
2134 toolMinor /= touchingCount;
2135 size /= touchingCount;
2136 }
2137 }
2138
Michael Wright227c5542020-07-02 18:30:52 +01002139 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002140 touchMajor *= mGeometricScale;
2141 touchMinor *= mGeometricScale;
2142 toolMajor *= mGeometricScale;
2143 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002144 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002145 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2146 touchMinor = touchMajor;
2147 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2148 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002149 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002150 touchMinor = touchMajor;
2151 toolMinor = toolMajor;
2152 }
2153
2154 mCalibration.applySizeScaleAndBias(&touchMajor);
2155 mCalibration.applySizeScaleAndBias(&touchMinor);
2156 mCalibration.applySizeScaleAndBias(&toolMajor);
2157 mCalibration.applySizeScaleAndBias(&toolMinor);
2158 size *= mSizeScale;
2159 break;
2160 default:
2161 touchMajor = 0;
2162 touchMinor = 0;
2163 toolMajor = 0;
2164 toolMinor = 0;
2165 size = 0;
2166 break;
2167 }
2168
2169 // Pressure
2170 float pressure;
2171 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002172 case Calibration::PressureCalibration::PHYSICAL:
2173 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002174 pressure = in.pressure * mPressureScale;
2175 break;
2176 default:
2177 pressure = in.isHovering ? 0 : 1;
2178 break;
2179 }
2180
2181 // Tilt and Orientation
2182 float tilt;
2183 float orientation;
2184 if (mHaveTilt) {
2185 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2186 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2187 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2188 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2189 } else {
2190 tilt = 0;
2191
2192 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002193 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002194 orientation = in.orientation * mOrientationScale;
2195 break;
Michael Wright227c5542020-07-02 18:30:52 +01002196 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002197 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2198 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2199 if (c1 != 0 || c2 != 0) {
2200 orientation = atan2f(c1, c2) * 0.5f;
2201 float confidence = hypotf(c1, c2);
2202 float scale = 1.0f + confidence / 16.0f;
2203 touchMajor *= scale;
2204 touchMinor /= scale;
2205 toolMajor *= scale;
2206 toolMinor /= scale;
2207 } else {
2208 orientation = 0;
2209 }
2210 break;
2211 }
2212 default:
2213 orientation = 0;
2214 }
2215 }
2216
2217 // Distance
2218 float distance;
2219 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002220 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002221 distance = in.distance * mDistanceScale;
2222 break;
2223 default:
2224 distance = 0;
2225 }
2226
2227 // Coverage
2228 int32_t rawLeft, rawTop, rawRight, rawBottom;
2229 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002230 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002231 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2232 rawRight = in.toolMinor & 0x0000ffff;
2233 rawBottom = in.toolMajor & 0x0000ffff;
2234 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2235 break;
2236 default:
2237 rawLeft = rawTop = rawRight = rawBottom = 0;
2238 break;
2239 }
2240
2241 // Adjust X,Y coords for device calibration
2242 // TODO: Adjust coverage coords?
2243 float xTransformed = in.x, yTransformed = in.y;
2244 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002245 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002246
2247 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002248 float left, top, right, bottom;
2249
2250 switch (mSurfaceOrientation) {
2251 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002252 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2253 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2254 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2255 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2256 orientation -= M_PI_2;
2257 if (mOrientedRanges.haveOrientation &&
2258 orientation < mOrientedRanges.orientation.min) {
2259 orientation +=
2260 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2261 }
2262 break;
2263 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002264 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2265 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2266 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2267 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2268 orientation -= M_PI;
2269 if (mOrientedRanges.haveOrientation &&
2270 orientation < mOrientedRanges.orientation.min) {
2271 orientation +=
2272 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2273 }
2274 break;
2275 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002276 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2277 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2278 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2279 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2280 orientation += M_PI_2;
2281 if (mOrientedRanges.haveOrientation &&
2282 orientation > mOrientedRanges.orientation.max) {
2283 orientation -=
2284 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2285 }
2286 break;
2287 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002288 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2289 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2290 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2291 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2292 break;
2293 }
2294
2295 // Write output coords.
2296 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2297 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002298 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2299 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002300 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2301 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2302 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2303 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2304 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2305 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2306 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002307 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002308 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2309 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2310 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2311 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2312 } else {
2313 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2314 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2315 }
2316
Chris Ye364fdb52020-08-05 15:07:56 -07002317 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002318 uint32_t id = in.id;
2319 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2320 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2321 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2322 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2323 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2324 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2325 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2326 }
2327
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002328 // Write output properties.
2329 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002330 properties.clear();
2331 properties.id = id;
2332 properties.toolType = in.toolType;
2333
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002334 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002335 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002336 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002337 }
2338}
2339
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002340void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002341 PointerUsage pointerUsage) {
2342 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002343 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 mPointerUsage = pointerUsage;
2345 }
2346
2347 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002348 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002349 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002350 break;
Michael Wright227c5542020-07-02 18:30:52 +01002351 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002352 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353 break;
Michael Wright227c5542020-07-02 18:30:52 +01002354 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002355 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 break;
Michael Wright227c5542020-07-02 18:30:52 +01002357 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 break;
2359 }
2360}
2361
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002362void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002363 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002364 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002365 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 break;
Michael Wright227c5542020-07-02 18:30:52 +01002367 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002368 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 break;
Michael Wright227c5542020-07-02 18:30:52 +01002370 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002371 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 break;
Michael Wright227c5542020-07-02 18:30:52 +01002373 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 break;
2375 }
2376
Michael Wright227c5542020-07-02 18:30:52 +01002377 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378}
2379
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002380void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2381 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 // Update current gesture coordinates.
2383 bool cancelPreviousGesture, finishPreviousGesture;
2384 bool sendEvents =
2385 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2386 if (!sendEvents) {
2387 return;
2388 }
2389 if (finishPreviousGesture) {
2390 cancelPreviousGesture = false;
2391 }
2392
2393 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002394 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002395 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 if (finishPreviousGesture || cancelPreviousGesture) {
2397 mPointerController->clearSpots();
2398 }
2399
Michael Wright227c5542020-07-02 18:30:52 +01002400 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002401 setTouchSpots(mPointerGesture.currentGestureCoords,
2402 mPointerGesture.currentGestureIdToIndex,
2403 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 }
2405 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002406 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002407 }
2408
2409 // Show or hide the pointer if needed.
2410 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002411 case PointerGesture::Mode::NEUTRAL:
2412 case PointerGesture::Mode::QUIET:
2413 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2414 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002416 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 }
2418 break;
Michael Wright227c5542020-07-02 18:30:52 +01002419 case PointerGesture::Mode::TAP:
2420 case PointerGesture::Mode::TAP_DRAG:
2421 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2422 case PointerGesture::Mode::HOVER:
2423 case PointerGesture::Mode::PRESS:
2424 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 // Unfade the pointer when the current gesture manipulates the
2426 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002427 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002428 break;
Michael Wright227c5542020-07-02 18:30:52 +01002429 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002430 // Fade the pointer when the current gesture manipulates a different
2431 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002432 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002433 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002435 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 }
2437 break;
2438 }
2439
2440 // Send events!
2441 int32_t metaState = getContext()->getGlobalMetaState();
2442 int32_t buttonState = mCurrentCookedState.buttonState;
2443
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002444 uint32_t flags = 0;
2445
2446 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2447 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2448 }
2449
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 // Update last coordinates of pointers that have moved so that we observe the new
2451 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002452 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2453 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2454 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2455 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2456 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2457 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 bool moveNeeded = false;
2459 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2460 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2461 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2462 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2463 mPointerGesture.lastGestureIdBits.value);
2464 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2465 mPointerGesture.currentGestureCoords,
2466 mPointerGesture.currentGestureIdToIndex,
2467 mPointerGesture.lastGestureProperties,
2468 mPointerGesture.lastGestureCoords,
2469 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2470 if (buttonState != mLastCookedState.buttonState) {
2471 moveNeeded = true;
2472 }
2473 }
2474
2475 // Send motion events for all pointers that went up or were canceled.
2476 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2477 if (!dispatchedGestureIdBits.isEmpty()) {
2478 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002479 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2480 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002481 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2482 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2483 mPointerGesture.downTime);
2484
2485 dispatchedGestureIdBits.clear();
2486 } else {
2487 BitSet32 upGestureIdBits;
2488 if (finishPreviousGesture) {
2489 upGestureIdBits = dispatchedGestureIdBits;
2490 } else {
2491 upGestureIdBits.value =
2492 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2493 }
2494 while (!upGestureIdBits.isEmpty()) {
2495 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2496
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002497 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002498 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002499 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002500 mPointerGesture.lastGestureCoords,
2501 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2502 0, mPointerGesture.downTime);
2503
2504 dispatchedGestureIdBits.clearBit(id);
2505 }
2506 }
2507 }
2508
2509 // Send motion events for all pointers that moved.
2510 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002511 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002512 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002513 mPointerGesture.currentGestureProperties,
2514 mPointerGesture.currentGestureCoords,
2515 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2516 mPointerGesture.downTime);
2517 }
2518
2519 // Send motion events for all pointers that went down.
2520 if (down) {
2521 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2522 ~dispatchedGestureIdBits.value);
2523 while (!downGestureIdBits.isEmpty()) {
2524 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2525 dispatchedGestureIdBits.markBit(id);
2526
2527 if (dispatchedGestureIdBits.count() == 1) {
2528 mPointerGesture.downTime = when;
2529 }
2530
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002531 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002532 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002533 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 mPointerGesture.currentGestureCoords,
2535 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2536 0, mPointerGesture.downTime);
2537 }
2538 }
2539
2540 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002541 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002542 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2543 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 mPointerGesture.currentGestureProperties,
2545 mPointerGesture.currentGestureCoords,
2546 mPointerGesture.currentGestureIdToIndex,
2547 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2548 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2549 // Synthesize a hover move event after all pointers go up to indicate that
2550 // the pointer is hovering again even if the user is not currently touching
2551 // the touch pad. This ensures that a view will receive a fresh hover enter
2552 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002553 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002554
2555 PointerProperties pointerProperties;
2556 pointerProperties.clear();
2557 pointerProperties.id = 0;
2558 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2559
2560 PointerCoords pointerCoords;
2561 pointerCoords.clear();
2562 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2563 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2564
2565 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002566 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002567 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002568 metaState, buttonState, MotionClassification::NONE,
2569 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2570 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002571 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002572 }
2573
2574 // Update state.
2575 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2576 if (!down) {
2577 mPointerGesture.lastGestureIdBits.clear();
2578 } else {
2579 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2580 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2581 uint32_t id = idBits.clearFirstMarkedBit();
2582 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2583 mPointerGesture.lastGestureProperties[index].copyFrom(
2584 mPointerGesture.currentGestureProperties[index]);
2585 mPointerGesture.lastGestureCoords[index].copyFrom(
2586 mPointerGesture.currentGestureCoords[index]);
2587 mPointerGesture.lastGestureIdToIndex[id] = index;
2588 }
2589 }
2590}
2591
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002592void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002593 // Cancel previously dispatches pointers.
2594 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2595 int32_t metaState = getContext()->getGlobalMetaState();
2596 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002597 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2598 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002599 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2600 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2601 0, 0, mPointerGesture.downTime);
2602 }
2603
2604 // Reset the current pointer gesture.
2605 mPointerGesture.reset();
2606 mPointerVelocityControl.reset();
2607
2608 // Remove any current spots.
2609 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002610 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002611 mPointerController->clearSpots();
2612 }
2613}
2614
2615bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2616 bool* outFinishPreviousGesture, bool isTimeout) {
2617 *outCancelPreviousGesture = false;
2618 *outFinishPreviousGesture = false;
2619
2620 // Handle TAP timeout.
2621 if (isTimeout) {
2622#if DEBUG_GESTURES
2623 ALOGD("Gestures: Processing timeout");
2624#endif
2625
Michael Wright227c5542020-07-02 18:30:52 +01002626 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002627 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2628 // The tap/drag timeout has not yet expired.
2629 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2630 mConfig.pointerGestureTapDragInterval);
2631 } else {
2632 // The tap is finished.
2633#if DEBUG_GESTURES
2634 ALOGD("Gestures: TAP finished");
2635#endif
2636 *outFinishPreviousGesture = true;
2637
2638 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002639 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002640 mPointerGesture.currentGestureIdBits.clear();
2641
2642 mPointerVelocityControl.reset();
2643 return true;
2644 }
2645 }
2646
2647 // We did not handle this timeout.
2648 return false;
2649 }
2650
2651 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2652 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2653
2654 // Update the velocity tracker.
2655 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002656 std::vector<VelocityTracker::Position> positions;
2657 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002658 uint32_t id = idBits.clearFirstMarkedBit();
2659 const RawPointerData::Pointer& pointer =
2660 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002661 float x = pointer.x * mPointerXMovementScale;
2662 float y = pointer.y * mPointerYMovementScale;
2663 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002664 }
2665 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2666 positions);
2667 }
2668
2669 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2670 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002671 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2672 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2673 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002674 mPointerGesture.resetTap();
2675 }
2676
2677 // Pick a new active touch id if needed.
2678 // Choose an arbitrary pointer that just went down, if there is one.
2679 // Otherwise choose an arbitrary remaining pointer.
2680 // This guarantees we always have an active touch id when there is at least one pointer.
2681 // We keep the same active touch id for as long as possible.
2682 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2683 int32_t activeTouchId = lastActiveTouchId;
2684 if (activeTouchId < 0) {
2685 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2686 activeTouchId = mPointerGesture.activeTouchId =
2687 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2688 mPointerGesture.firstTouchTime = when;
2689 }
2690 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2691 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2692 activeTouchId = mPointerGesture.activeTouchId =
2693 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2694 } else {
2695 activeTouchId = mPointerGesture.activeTouchId = -1;
2696 }
2697 }
2698
2699 // Determine whether we are in quiet time.
2700 bool isQuietTime = false;
2701 if (activeTouchId < 0) {
2702 mPointerGesture.resetQuietTime();
2703 } else {
2704 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2705 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002706 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2707 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2708 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002709 currentFingerCount < 2) {
2710 // Enter quiet time when exiting swipe or freeform state.
2711 // This is to prevent accidentally entering the hover state and flinging the
2712 // pointer when finishing a swipe and there is still one pointer left onscreen.
2713 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002714 } else if (mPointerGesture.lastGestureMode ==
2715 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002716 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2717 // Enter quiet time when releasing the button and there are still two or more
2718 // fingers down. This may indicate that one finger was used to press the button
2719 // but it has not gone up yet.
2720 isQuietTime = true;
2721 }
2722 if (isQuietTime) {
2723 mPointerGesture.quietTime = when;
2724 }
2725 }
2726 }
2727
2728 // Switch states based on button and pointer state.
2729 if (isQuietTime) {
2730 // Case 1: Quiet time. (QUIET)
2731#if DEBUG_GESTURES
2732 ALOGD("Gestures: QUIET for next %0.3fms",
2733 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2734#endif
Michael Wright227c5542020-07-02 18:30:52 +01002735 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002736 *outFinishPreviousGesture = true;
2737 }
2738
2739 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002740 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002741 mPointerGesture.currentGestureIdBits.clear();
2742
2743 mPointerVelocityControl.reset();
2744 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2745 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2746 // The pointer follows the active touch point.
2747 // Emit DOWN, MOVE, UP events at the pointer location.
2748 //
2749 // Only the active touch matters; other fingers are ignored. This policy helps
2750 // to handle the case where the user places a second finger on the touch pad
2751 // to apply the necessary force to depress an integrated button below the surface.
2752 // We don't want the second finger to be delivered to applications.
2753 //
2754 // For this to work well, we need to make sure to track the pointer that is really
2755 // active. If the user first puts one finger down to click then adds another
2756 // finger to drag then the active pointer should switch to the finger that is
2757 // being dragged.
2758#if DEBUG_GESTURES
2759 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2760 "currentFingerCount=%d",
2761 activeTouchId, currentFingerCount);
2762#endif
2763 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002764 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002765 *outFinishPreviousGesture = true;
2766 mPointerGesture.activeGestureId = 0;
2767 }
2768
2769 // Switch pointers if needed.
2770 // Find the fastest pointer and follow it.
2771 if (activeTouchId >= 0 && currentFingerCount > 1) {
2772 int32_t bestId = -1;
2773 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2774 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2775 uint32_t id = idBits.clearFirstMarkedBit();
2776 float vx, vy;
2777 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2778 float speed = hypotf(vx, vy);
2779 if (speed > bestSpeed) {
2780 bestId = id;
2781 bestSpeed = speed;
2782 }
2783 }
2784 }
2785 if (bestId >= 0 && bestId != activeTouchId) {
2786 mPointerGesture.activeTouchId = activeTouchId = bestId;
2787#if DEBUG_GESTURES
2788 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2789 "bestId=%d, bestSpeed=%0.3f",
2790 bestId, bestSpeed);
2791#endif
2792 }
2793 }
2794
2795 float deltaX = 0, deltaY = 0;
2796 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2797 const RawPointerData::Pointer& currentPointer =
2798 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2799 const RawPointerData::Pointer& lastPointer =
2800 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2801 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2802 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2803
2804 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2805 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2806
2807 // Move the pointer using a relative motion.
2808 // When using spots, the click will occur at the position of the anchor
2809 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002810 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002811 } else {
2812 mPointerVelocityControl.reset();
2813 }
2814
Prabir Pradhand7482e72021-03-09 13:54:55 -08002815 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002816
Michael Wright227c5542020-07-02 18:30:52 +01002817 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002818 mPointerGesture.currentGestureIdBits.clear();
2819 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2820 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2821 mPointerGesture.currentGestureProperties[0].clear();
2822 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2823 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2824 mPointerGesture.currentGestureCoords[0].clear();
2825 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2826 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2827 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2828 } else if (currentFingerCount == 0) {
2829 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002830 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002831 *outFinishPreviousGesture = true;
2832 }
2833
2834 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2835 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2836 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002837 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2838 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002839 lastFingerCount == 1) {
2840 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002841 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002842 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2843 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2844#if DEBUG_GESTURES
2845 ALOGD("Gestures: TAP");
2846#endif
2847
2848 mPointerGesture.tapUpTime = when;
2849 getContext()->requestTimeoutAtTime(when +
2850 mConfig.pointerGestureTapDragInterval);
2851
2852 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002853 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 mPointerGesture.currentGestureIdBits.clear();
2855 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2856 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2857 mPointerGesture.currentGestureProperties[0].clear();
2858 mPointerGesture.currentGestureProperties[0].id =
2859 mPointerGesture.activeGestureId;
2860 mPointerGesture.currentGestureProperties[0].toolType =
2861 AMOTION_EVENT_TOOL_TYPE_FINGER;
2862 mPointerGesture.currentGestureCoords[0].clear();
2863 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2864 mPointerGesture.tapX);
2865 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2866 mPointerGesture.tapY);
2867 mPointerGesture.currentGestureCoords[0]
2868 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2869
2870 tapped = true;
2871 } else {
2872#if DEBUG_GESTURES
2873 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2874 y - mPointerGesture.tapY);
2875#endif
2876 }
2877 } else {
2878#if DEBUG_GESTURES
2879 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2880 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2881 (when - mPointerGesture.tapDownTime) * 0.000001f);
2882 } else {
2883 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2884 }
2885#endif
2886 }
2887 }
2888
2889 mPointerVelocityControl.reset();
2890
2891 if (!tapped) {
2892#if DEBUG_GESTURES
2893 ALOGD("Gestures: NEUTRAL");
2894#endif
2895 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002896 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002897 mPointerGesture.currentGestureIdBits.clear();
2898 }
2899 } else if (currentFingerCount == 1) {
2900 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2901 // The pointer follows the active touch point.
2902 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2903 // When in TAP_DRAG, emit MOVE events at the pointer location.
2904 ALOG_ASSERT(activeTouchId >= 0);
2905
Michael Wright227c5542020-07-02 18:30:52 +01002906 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2907 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002908 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002909 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2911 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002912 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913 } else {
2914#if DEBUG_GESTURES
2915 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2916 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2917#endif
2918 }
2919 } else {
2920#if DEBUG_GESTURES
2921 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2922 (when - mPointerGesture.tapUpTime) * 0.000001f);
2923#endif
2924 }
Michael Wright227c5542020-07-02 18:30:52 +01002925 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2926 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002927 }
2928
2929 float deltaX = 0, deltaY = 0;
2930 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2931 const RawPointerData::Pointer& currentPointer =
2932 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2933 const RawPointerData::Pointer& lastPointer =
2934 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2935 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2936 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2937
2938 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2939 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2940
2941 // Move the pointer using a relative motion.
2942 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002943 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 } else {
2945 mPointerVelocityControl.reset();
2946 }
2947
2948 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002949 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950#if DEBUG_GESTURES
2951 ALOGD("Gestures: TAP_DRAG");
2952#endif
2953 down = true;
2954 } else {
2955#if DEBUG_GESTURES
2956 ALOGD("Gestures: HOVER");
2957#endif
Michael Wright227c5542020-07-02 18:30:52 +01002958 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002959 *outFinishPreviousGesture = true;
2960 }
2961 mPointerGesture.activeGestureId = 0;
2962 down = false;
2963 }
2964
Prabir Pradhand7482e72021-03-09 13:54:55 -08002965 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002966
2967 mPointerGesture.currentGestureIdBits.clear();
2968 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2969 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2970 mPointerGesture.currentGestureProperties[0].clear();
2971 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2972 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2973 mPointerGesture.currentGestureCoords[0].clear();
2974 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2975 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2976 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2977 down ? 1.0f : 0.0f);
2978
2979 if (lastFingerCount == 0 && currentFingerCount != 0) {
2980 mPointerGesture.resetTap();
2981 mPointerGesture.tapDownTime = when;
2982 mPointerGesture.tapX = x;
2983 mPointerGesture.tapY = y;
2984 }
2985 } else {
2986 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2987 // We need to provide feedback for each finger that goes down so we cannot wait
2988 // for the fingers to move before deciding what to do.
2989 //
2990 // The ambiguous case is deciding what to do when there are two fingers down but they
2991 // have not moved enough to determine whether they are part of a drag or part of a
2992 // freeform gesture, or just a press or long-press at the pointer location.
2993 //
2994 // When there are two fingers we start with the PRESS hypothesis and we generate a
2995 // down at the pointer location.
2996 //
2997 // When the two fingers move enough or when additional fingers are added, we make
2998 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2999 ALOG_ASSERT(activeTouchId >= 0);
3000
3001 bool settled = when >=
3002 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003003 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3004 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3005 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003006 *outFinishPreviousGesture = true;
3007 } else if (!settled && currentFingerCount > lastFingerCount) {
3008 // Additional pointers have gone down but not yet settled.
3009 // Reset the gesture.
3010#if DEBUG_GESTURES
3011 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3012 "settle time remaining %0.3fms",
3013 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3014 when) * 0.000001f);
3015#endif
3016 *outCancelPreviousGesture = true;
3017 } else {
3018 // Continue previous gesture.
3019 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3020 }
3021
3022 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003023 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003024 mPointerGesture.activeGestureId = 0;
3025 mPointerGesture.referenceIdBits.clear();
3026 mPointerVelocityControl.reset();
3027
3028 // Use the centroid and pointer location as the reference points for the gesture.
3029#if DEBUG_GESTURES
3030 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3031 "settle time remaining %0.3fms",
3032 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3033 when) * 0.000001f);
3034#endif
3035 mCurrentRawState.rawPointerData
3036 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3037 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003038 auto [x, y] = getMouseCursorPosition();
3039 mPointerGesture.referenceGestureX = x;
3040 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003041 }
3042
3043 // Clear the reference deltas for fingers not yet included in the reference calculation.
3044 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3045 ~mPointerGesture.referenceIdBits.value);
3046 !idBits.isEmpty();) {
3047 uint32_t id = idBits.clearFirstMarkedBit();
3048 mPointerGesture.referenceDeltas[id].dx = 0;
3049 mPointerGesture.referenceDeltas[id].dy = 0;
3050 }
3051 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3052
3053 // Add delta for all fingers and calculate a common movement delta.
3054 float commonDeltaX = 0, commonDeltaY = 0;
3055 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3056 mCurrentCookedState.fingerIdBits.value);
3057 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3058 bool first = (idBits == commonIdBits);
3059 uint32_t id = idBits.clearFirstMarkedBit();
3060 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3061 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3062 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3063 delta.dx += cpd.x - lpd.x;
3064 delta.dy += cpd.y - lpd.y;
3065
3066 if (first) {
3067 commonDeltaX = delta.dx;
3068 commonDeltaY = delta.dy;
3069 } else {
3070 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3071 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3072 }
3073 }
3074
3075 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003076 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003077 float dist[MAX_POINTER_ID + 1];
3078 int32_t distOverThreshold = 0;
3079 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3080 uint32_t id = idBits.clearFirstMarkedBit();
3081 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3082 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3083 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3084 distOverThreshold += 1;
3085 }
3086 }
3087
3088 // Only transition when at least two pointers have moved further than
3089 // the minimum distance threshold.
3090 if (distOverThreshold >= 2) {
3091 if (currentFingerCount > 2) {
3092 // There are more than two pointers, switch to FREEFORM.
3093#if DEBUG_GESTURES
3094 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3095 currentFingerCount);
3096#endif
3097 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003098 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003099 } else {
3100 // There are exactly two pointers.
3101 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3102 uint32_t id1 = idBits.clearFirstMarkedBit();
3103 uint32_t id2 = idBits.firstMarkedBit();
3104 const RawPointerData::Pointer& p1 =
3105 mCurrentRawState.rawPointerData.pointerForId(id1);
3106 const RawPointerData::Pointer& p2 =
3107 mCurrentRawState.rawPointerData.pointerForId(id2);
3108 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3109 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3110 // There are two pointers but they are too far apart for a SWIPE,
3111 // switch to FREEFORM.
3112#if DEBUG_GESTURES
3113 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3114 mutualDistance, mPointerGestureMaxSwipeWidth);
3115#endif
3116 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003117 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003118 } else {
3119 // There are two pointers. Wait for both pointers to start moving
3120 // before deciding whether this is a SWIPE or FREEFORM gesture.
3121 float dist1 = dist[id1];
3122 float dist2 = dist[id2];
3123 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3124 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3125 // Calculate the dot product of the displacement vectors.
3126 // When the vectors are oriented in approximately the same direction,
3127 // the angle betweeen them is near zero and the cosine of the angle
3128 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3129 // mag(v2).
3130 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3131 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3132 float dx1 = delta1.dx * mPointerXZoomScale;
3133 float dy1 = delta1.dy * mPointerYZoomScale;
3134 float dx2 = delta2.dx * mPointerXZoomScale;
3135 float dy2 = delta2.dy * mPointerYZoomScale;
3136 float dot = dx1 * dx2 + dy1 * dy2;
3137 float cosine = dot / (dist1 * dist2); // denominator always > 0
3138 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3139 // Pointers are moving in the same direction. Switch to SWIPE.
3140#if DEBUG_GESTURES
3141 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3142 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3143 "cosine %0.3f >= %0.3f",
3144 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3145 mConfig.pointerGestureMultitouchMinDistance, cosine,
3146 mConfig.pointerGestureSwipeTransitionAngleCosine);
3147#endif
Michael Wright227c5542020-07-02 18:30:52 +01003148 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003149 } else {
3150 // Pointers are moving in different directions. Switch to FREEFORM.
3151#if DEBUG_GESTURES
3152 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3153 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3154 "cosine %0.3f < %0.3f",
3155 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3156 mConfig.pointerGestureMultitouchMinDistance, cosine,
3157 mConfig.pointerGestureSwipeTransitionAngleCosine);
3158#endif
3159 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003160 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003161 }
3162 }
3163 }
3164 }
3165 }
Michael Wright227c5542020-07-02 18:30:52 +01003166 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003167 // Switch from SWIPE to FREEFORM if additional pointers go down.
3168 // Cancel previous gesture.
3169 if (currentFingerCount > 2) {
3170#if DEBUG_GESTURES
3171 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3172 currentFingerCount);
3173#endif
3174 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003175 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003176 }
3177 }
3178
3179 // Move the reference points based on the overall group motion of the fingers
3180 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003181 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003182 (commonDeltaX || commonDeltaY)) {
3183 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3184 uint32_t id = idBits.clearFirstMarkedBit();
3185 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3186 delta.dx = 0;
3187 delta.dy = 0;
3188 }
3189
3190 mPointerGesture.referenceTouchX += commonDeltaX;
3191 mPointerGesture.referenceTouchY += commonDeltaY;
3192
3193 commonDeltaX *= mPointerXMovementScale;
3194 commonDeltaY *= mPointerYMovementScale;
3195
3196 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3197 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3198
3199 mPointerGesture.referenceGestureX += commonDeltaX;
3200 mPointerGesture.referenceGestureY += commonDeltaY;
3201 }
3202
3203 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003204 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3205 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003206 // PRESS or SWIPE mode.
3207#if DEBUG_GESTURES
3208 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3209 "activeGestureId=%d, currentTouchPointerCount=%d",
3210 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3211#endif
3212 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3213
3214 mPointerGesture.currentGestureIdBits.clear();
3215 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3216 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3217 mPointerGesture.currentGestureProperties[0].clear();
3218 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3219 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3220 mPointerGesture.currentGestureCoords[0].clear();
3221 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3222 mPointerGesture.referenceGestureX);
3223 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3224 mPointerGesture.referenceGestureY);
3225 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003226 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003227 // FREEFORM mode.
3228#if DEBUG_GESTURES
3229 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3230 "activeGestureId=%d, currentTouchPointerCount=%d",
3231 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3232#endif
3233 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3234
3235 mPointerGesture.currentGestureIdBits.clear();
3236
3237 BitSet32 mappedTouchIdBits;
3238 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003239 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003240 // Initially, assign the active gesture id to the active touch point
3241 // if there is one. No other touch id bits are mapped yet.
3242 if (!*outCancelPreviousGesture) {
3243 mappedTouchIdBits.markBit(activeTouchId);
3244 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3245 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3246 mPointerGesture.activeGestureId;
3247 } else {
3248 mPointerGesture.activeGestureId = -1;
3249 }
3250 } else {
3251 // Otherwise, assume we mapped all touches from the previous frame.
3252 // Reuse all mappings that are still applicable.
3253 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3254 mCurrentCookedState.fingerIdBits.value;
3255 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3256
3257 // Check whether we need to choose a new active gesture id because the
3258 // current went went up.
3259 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3260 ~mCurrentCookedState.fingerIdBits.value);
3261 !upTouchIdBits.isEmpty();) {
3262 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3263 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3264 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3265 mPointerGesture.activeGestureId = -1;
3266 break;
3267 }
3268 }
3269 }
3270
3271#if DEBUG_GESTURES
3272 ALOGD("Gestures: FREEFORM follow up "
3273 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3274 "activeGestureId=%d",
3275 mappedTouchIdBits.value, usedGestureIdBits.value,
3276 mPointerGesture.activeGestureId);
3277#endif
3278
3279 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3280 for (uint32_t i = 0; i < currentFingerCount; i++) {
3281 uint32_t touchId = idBits.clearFirstMarkedBit();
3282 uint32_t gestureId;
3283 if (!mappedTouchIdBits.hasBit(touchId)) {
3284 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3285 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3286#if DEBUG_GESTURES
3287 ALOGD("Gestures: FREEFORM "
3288 "new mapping for touch id %d -> gesture id %d",
3289 touchId, gestureId);
3290#endif
3291 } else {
3292 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3293#if DEBUG_GESTURES
3294 ALOGD("Gestures: FREEFORM "
3295 "existing mapping for touch id %d -> gesture id %d",
3296 touchId, gestureId);
3297#endif
3298 }
3299 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3300 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3301
3302 const RawPointerData::Pointer& pointer =
3303 mCurrentRawState.rawPointerData.pointerForId(touchId);
3304 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3305 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3306 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3307
3308 mPointerGesture.currentGestureProperties[i].clear();
3309 mPointerGesture.currentGestureProperties[i].id = gestureId;
3310 mPointerGesture.currentGestureProperties[i].toolType =
3311 AMOTION_EVENT_TOOL_TYPE_FINGER;
3312 mPointerGesture.currentGestureCoords[i].clear();
3313 mPointerGesture.currentGestureCoords[i]
3314 .setAxisValue(AMOTION_EVENT_AXIS_X,
3315 mPointerGesture.referenceGestureX + deltaX);
3316 mPointerGesture.currentGestureCoords[i]
3317 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3318 mPointerGesture.referenceGestureY + deltaY);
3319 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3320 1.0f);
3321 }
3322
3323 if (mPointerGesture.activeGestureId < 0) {
3324 mPointerGesture.activeGestureId =
3325 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3326#if DEBUG_GESTURES
3327 ALOGD("Gestures: FREEFORM new "
3328 "activeGestureId=%d",
3329 mPointerGesture.activeGestureId);
3330#endif
3331 }
3332 }
3333 }
3334
3335 mPointerController->setButtonState(mCurrentRawState.buttonState);
3336
3337#if DEBUG_GESTURES
3338 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3339 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3340 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3341 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3342 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3343 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3344 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3345 uint32_t id = idBits.clearFirstMarkedBit();
3346 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3347 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3348 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3349 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3350 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3351 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3352 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3353 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3354 }
3355 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3356 uint32_t id = idBits.clearFirstMarkedBit();
3357 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3358 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3359 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3360 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3361 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3362 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3363 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3364 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3365 }
3366#endif
3367 return true;
3368}
3369
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003370void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003371 mPointerSimple.currentCoords.clear();
3372 mPointerSimple.currentProperties.clear();
3373
3374 bool down, hovering;
3375 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3376 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3377 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003378 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3379 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003380
3381 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3382 down = !hovering;
3383
Prabir Pradhand7482e72021-03-09 13:54:55 -08003384 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003385 mPointerSimple.currentCoords.copyFrom(
3386 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3387 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3388 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3389 mPointerSimple.currentProperties.id = 0;
3390 mPointerSimple.currentProperties.toolType =
3391 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3392 } else {
3393 down = false;
3394 hovering = false;
3395 }
3396
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003397 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003398}
3399
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003400void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3401 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003402}
3403
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003404void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003405 mPointerSimple.currentCoords.clear();
3406 mPointerSimple.currentProperties.clear();
3407
3408 bool down, hovering;
3409 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3410 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3411 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3412 float deltaX = 0, deltaY = 0;
3413 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3414 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3415 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3416 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3417 mPointerXMovementScale;
3418 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3419 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3420 mPointerYMovementScale;
3421
3422 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3423 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3424
Prabir Pradhand7482e72021-03-09 13:54:55 -08003425 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003426 } else {
3427 mPointerVelocityControl.reset();
3428 }
3429
3430 down = isPointerDown(mCurrentRawState.buttonState);
3431 hovering = !down;
3432
Prabir Pradhand7482e72021-03-09 13:54:55 -08003433 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003434 mPointerSimple.currentCoords.copyFrom(
3435 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3436 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3437 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3438 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3439 hovering ? 0.0f : 1.0f);
3440 mPointerSimple.currentProperties.id = 0;
3441 mPointerSimple.currentProperties.toolType =
3442 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3443 } else {
3444 mPointerVelocityControl.reset();
3445
3446 down = false;
3447 hovering = false;
3448 }
3449
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003450 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003451}
3452
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003453void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3454 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003455
3456 mPointerVelocityControl.reset();
3457}
3458
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003459void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3460 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003461 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003462
3463 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003464 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003465 mPointerController->clearSpots();
3466 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003467 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003468 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003469 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003470 }
Garfield Tan9514d782020-11-10 16:37:23 -08003471 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003472
Prabir Pradhand7482e72021-03-09 13:54:55 -08003473 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003474
3475 if (mPointerSimple.down && !down) {
3476 mPointerSimple.down = false;
3477
3478 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003479 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3480 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003481 mLastRawState.buttonState, MotionClassification::NONE,
3482 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3483 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3484 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3485 /* videoFrames */ {});
3486 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003487 }
3488
3489 if (mPointerSimple.hovering && !hovering) {
3490 mPointerSimple.hovering = false;
3491
3492 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003493 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3494 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3495 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003496 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3497 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3498 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3499 /* videoFrames */ {});
3500 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003501 }
3502
3503 if (down) {
3504 if (!mPointerSimple.down) {
3505 mPointerSimple.down = true;
3506 mPointerSimple.downTime = when;
3507
3508 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003509 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003510 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3511 metaState, mCurrentRawState.buttonState,
3512 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3513 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3514 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3515 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3516 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517 }
3518
3519 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003520 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3521 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003522 mCurrentRawState.buttonState, MotionClassification::NONE,
3523 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3524 &mPointerSimple.currentCoords, mOrientedXPrecision,
3525 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3526 mPointerSimple.downTime, /* videoFrames */ {});
3527 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003528 }
3529
3530 if (hovering) {
3531 if (!mPointerSimple.hovering) {
3532 mPointerSimple.hovering = true;
3533
3534 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003535 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003536 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3537 metaState, mCurrentRawState.buttonState,
3538 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3539 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3540 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3541 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3542 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003543 }
3544
3545 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003546 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3547 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3548 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003549 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3550 &mPointerSimple.currentCoords, mOrientedXPrecision,
3551 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3552 mPointerSimple.downTime, /* videoFrames */ {});
3553 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003554 }
3555
3556 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3557 float vscroll = mCurrentRawState.rawVScroll;
3558 float hscroll = mCurrentRawState.rawHScroll;
3559 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3560 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3561
3562 // Send scroll.
3563 PointerCoords pointerCoords;
3564 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3565 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3566 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3567
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003568 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3569 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003570 mCurrentRawState.buttonState, MotionClassification::NONE,
3571 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3572 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3573 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3574 /* videoFrames */ {});
3575 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003576 }
3577
3578 // Save state.
3579 if (down || hovering) {
3580 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3581 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3582 } else {
3583 mPointerSimple.reset();
3584 }
3585}
3586
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003587void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003588 mPointerSimple.currentCoords.clear();
3589 mPointerSimple.currentProperties.clear();
3590
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003591 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003592}
3593
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003594void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3595 uint32_t source, int32_t action, int32_t actionButton,
3596 int32_t flags, int32_t metaState, int32_t buttonState,
3597 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598 const PointerCoords* coords, const uint32_t* idToIndex,
3599 BitSet32 idBits, int32_t changedId, float xPrecision,
3600 float yPrecision, nsecs_t downTime) {
3601 PointerCoords pointerCoords[MAX_POINTERS];
3602 PointerProperties pointerProperties[MAX_POINTERS];
3603 uint32_t pointerCount = 0;
3604 while (!idBits.isEmpty()) {
3605 uint32_t id = idBits.clearFirstMarkedBit();
3606 uint32_t index = idToIndex[id];
3607 pointerProperties[pointerCount].copyFrom(properties[index]);
3608 pointerCoords[pointerCount].copyFrom(coords[index]);
3609
3610 if (changedId >= 0 && id == uint32_t(changedId)) {
3611 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3612 }
3613
3614 pointerCount += 1;
3615 }
3616
3617 ALOG_ASSERT(pointerCount != 0);
3618
3619 if (changedId >= 0 && pointerCount == 1) {
3620 // Replace initial down and final up action.
3621 // We can compare the action without masking off the changed pointer index
3622 // because we know the index is 0.
3623 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3624 action = AMOTION_EVENT_ACTION_DOWN;
3625 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003626 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3627 action = AMOTION_EVENT_ACTION_CANCEL;
3628 } else {
3629 action = AMOTION_EVENT_ACTION_UP;
3630 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003631 } else {
3632 // Can't happen.
3633 ALOG_ASSERT(false);
3634 }
3635 }
3636 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3637 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003638 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003639 auto [x, y] = getMouseCursorPosition();
3640 xCursorPosition = x;
3641 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003642 }
3643 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3644 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003645 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003646 std::for_each(frames.begin(), frames.end(),
3647 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003648 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3649 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003650 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3651 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3652 downTime, std::move(frames));
3653 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003654}
3655
3656bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3657 const PointerCoords* inCoords,
3658 const uint32_t* inIdToIndex,
3659 PointerProperties* outProperties,
3660 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3661 BitSet32 idBits) const {
3662 bool changed = false;
3663 while (!idBits.isEmpty()) {
3664 uint32_t id = idBits.clearFirstMarkedBit();
3665 uint32_t inIndex = inIdToIndex[id];
3666 uint32_t outIndex = outIdToIndex[id];
3667
3668 const PointerProperties& curInProperties = inProperties[inIndex];
3669 const PointerCoords& curInCoords = inCoords[inIndex];
3670 PointerProperties& curOutProperties = outProperties[outIndex];
3671 PointerCoords& curOutCoords = outCoords[outIndex];
3672
3673 if (curInProperties != curOutProperties) {
3674 curOutProperties.copyFrom(curInProperties);
3675 changed = true;
3676 }
3677
3678 if (curInCoords != curOutCoords) {
3679 curOutCoords.copyFrom(curInCoords);
3680 changed = true;
3681 }
3682 }
3683 return changed;
3684}
3685
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003686void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3687 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3688 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003689}
3690
Arthur Hung4197f6b2020-03-16 15:39:59 +08003691// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003692void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003693 // Scale to surface coordinate.
3694 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3695 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3696
arthurhunga36b28e2020-12-29 20:28:15 +08003697 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3698 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3699
Arthur Hung4197f6b2020-03-16 15:39:59 +08003700 // Rotate to surface coordinate.
3701 // 0 - no swap and reverse.
3702 // 90 - swap x/y and reverse y.
3703 // 180 - reverse x, y.
3704 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003705 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003706 case DISPLAY_ORIENTATION_0:
3707 x = xScaled + mXTranslate;
3708 y = yScaled + mYTranslate;
3709 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003710 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003711 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003712 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003713 break;
3714 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003715 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3716 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003717 break;
3718 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003719 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003720 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003721 break;
3722 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003723 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003724 }
3725}
3726
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003727bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003728 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3729 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3730
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003731 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003732 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003733 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003734 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003735}
3736
3737const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3738 for (const VirtualKey& virtualKey : mVirtualKeys) {
3739#if DEBUG_VIRTUAL_KEYS
3740 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3741 "left=%d, top=%d, right=%d, bottom=%d",
3742 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3743 virtualKey.hitRight, virtualKey.hitBottom);
3744#endif
3745
3746 if (virtualKey.isHit(x, y)) {
3747 return &virtualKey;
3748 }
3749 }
3750
3751 return nullptr;
3752}
3753
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003754void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3755 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3756 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003757
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003758 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003759
3760 if (currentPointerCount == 0) {
3761 // No pointers to assign.
3762 return;
3763 }
3764
3765 if (lastPointerCount == 0) {
3766 // All pointers are new.
3767 for (uint32_t i = 0; i < currentPointerCount; i++) {
3768 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003769 current.rawPointerData.pointers[i].id = id;
3770 current.rawPointerData.idToIndex[id] = i;
3771 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003772 }
3773 return;
3774 }
3775
3776 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003777 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003778 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003779 uint32_t id = last.rawPointerData.pointers[0].id;
3780 current.rawPointerData.pointers[0].id = id;
3781 current.rawPointerData.idToIndex[id] = 0;
3782 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003783 return;
3784 }
3785
3786 // General case.
3787 // We build a heap of squared euclidean distances between current and last pointers
3788 // associated with the current and last pointer indices. Then, we find the best
3789 // match (by distance) for each current pointer.
3790 // The pointers must have the same tool type but it is possible for them to
3791 // transition from hovering to touching or vice-versa while retaining the same id.
3792 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3793
3794 uint32_t heapSize = 0;
3795 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3796 currentPointerIndex++) {
3797 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3798 lastPointerIndex++) {
3799 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003800 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003801 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003802 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003803 if (currentPointer.toolType == lastPointer.toolType) {
3804 int64_t deltaX = currentPointer.x - lastPointer.x;
3805 int64_t deltaY = currentPointer.y - lastPointer.y;
3806
3807 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3808
3809 // Insert new element into the heap (sift up).
3810 heap[heapSize].currentPointerIndex = currentPointerIndex;
3811 heap[heapSize].lastPointerIndex = lastPointerIndex;
3812 heap[heapSize].distance = distance;
3813 heapSize += 1;
3814 }
3815 }
3816 }
3817
3818 // Heapify
3819 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3820 startIndex -= 1;
3821 for (uint32_t parentIndex = startIndex;;) {
3822 uint32_t childIndex = parentIndex * 2 + 1;
3823 if (childIndex >= heapSize) {
3824 break;
3825 }
3826
3827 if (childIndex + 1 < heapSize &&
3828 heap[childIndex + 1].distance < heap[childIndex].distance) {
3829 childIndex += 1;
3830 }
3831
3832 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3833 break;
3834 }
3835
3836 swap(heap[parentIndex], heap[childIndex]);
3837 parentIndex = childIndex;
3838 }
3839 }
3840
3841#if DEBUG_POINTER_ASSIGNMENT
3842 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3843 for (size_t i = 0; i < heapSize; i++) {
3844 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3845 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3846 }
3847#endif
3848
3849 // Pull matches out by increasing order of distance.
3850 // To avoid reassigning pointers that have already been matched, the loop keeps track
3851 // of which last and current pointers have been matched using the matchedXXXBits variables.
3852 // It also tracks the used pointer id bits.
3853 BitSet32 matchedLastBits(0);
3854 BitSet32 matchedCurrentBits(0);
3855 BitSet32 usedIdBits(0);
3856 bool first = true;
3857 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3858 while (heapSize > 0) {
3859 if (first) {
3860 // The first time through the loop, we just consume the root element of
3861 // the heap (the one with smallest distance).
3862 first = false;
3863 } else {
3864 // Previous iterations consumed the root element of the heap.
3865 // Pop root element off of the heap (sift down).
3866 heap[0] = heap[heapSize];
3867 for (uint32_t parentIndex = 0;;) {
3868 uint32_t childIndex = parentIndex * 2 + 1;
3869 if (childIndex >= heapSize) {
3870 break;
3871 }
3872
3873 if (childIndex + 1 < heapSize &&
3874 heap[childIndex + 1].distance < heap[childIndex].distance) {
3875 childIndex += 1;
3876 }
3877
3878 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3879 break;
3880 }
3881
3882 swap(heap[parentIndex], heap[childIndex]);
3883 parentIndex = childIndex;
3884 }
3885
3886#if DEBUG_POINTER_ASSIGNMENT
3887 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003888 for (size_t j = 0; j < heapSize; j++) {
3889 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3890 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003891 }
3892#endif
3893 }
3894
3895 heapSize -= 1;
3896
3897 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3898 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3899
3900 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3901 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3902
3903 matchedCurrentBits.markBit(currentPointerIndex);
3904 matchedLastBits.markBit(lastPointerIndex);
3905
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003906 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3907 current.rawPointerData.pointers[currentPointerIndex].id = id;
3908 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3909 current.rawPointerData.markIdBit(id,
3910 current.rawPointerData.isHovering(
3911 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003912 usedIdBits.markBit(id);
3913
3914#if DEBUG_POINTER_ASSIGNMENT
3915 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3916 ", distance=%" PRIu64,
3917 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3918#endif
3919 break;
3920 }
3921 }
3922
3923 // Assign fresh ids to pointers that were not matched in the process.
3924 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3925 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3926 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3927
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003928 current.rawPointerData.pointers[currentPointerIndex].id = id;
3929 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3930 current.rawPointerData.markIdBit(id,
3931 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003932
3933#if DEBUG_POINTER_ASSIGNMENT
3934 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3935#endif
3936 }
3937}
3938
3939int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3940 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3941 return AKEY_STATE_VIRTUAL;
3942 }
3943
3944 for (const VirtualKey& virtualKey : mVirtualKeys) {
3945 if (virtualKey.keyCode == keyCode) {
3946 return AKEY_STATE_UP;
3947 }
3948 }
3949
3950 return AKEY_STATE_UNKNOWN;
3951}
3952
3953int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3954 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3955 return AKEY_STATE_VIRTUAL;
3956 }
3957
3958 for (const VirtualKey& virtualKey : mVirtualKeys) {
3959 if (virtualKey.scanCode == scanCode) {
3960 return AKEY_STATE_UP;
3961 }
3962 }
3963
3964 return AKEY_STATE_UNKNOWN;
3965}
3966
3967bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3968 const int32_t* keyCodes, uint8_t* outFlags) {
3969 for (const VirtualKey& virtualKey : mVirtualKeys) {
3970 for (size_t i = 0; i < numCodes; i++) {
3971 if (virtualKey.keyCode == keyCodes[i]) {
3972 outFlags[i] = 1;
3973 }
3974 }
3975 }
3976
3977 return true;
3978}
3979
3980std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3981 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003982 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003983 return std::make_optional(mPointerController->getDisplayId());
3984 } else {
3985 return std::make_optional(mViewport.displayId);
3986 }
3987 }
3988 return std::nullopt;
3989}
3990
Prabir Pradhand7482e72021-03-09 13:54:55 -08003991void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
3992 if (isPerWindowInputRotationEnabled()) {
3993 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
3994 // space that is oriented with the viewport.
3995 rotateDelta(mViewport.orientation, &dx, &dy);
3996 }
3997
3998 mPointerController->move(dx, dy);
3999}
4000
4001std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4002 float x = 0;
4003 float y = 0;
4004 mPointerController->getPosition(&x, &y);
4005
4006 if (!isPerWindowInputRotationEnabled()) return {x, y};
4007 if (!mViewport.isValid()) return {x, y};
4008
4009 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4010 // to InputReader's un-rotated coordinate space.
4011 const int32_t orientation = getInverseRotation(mViewport.orientation);
4012 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4013 return {x, y};
4014}
4015
4016void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4017 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4018 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4019 // coordinate space that is oriented with the viewport.
4020 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4021 }
4022
4023 mPointerController->setPosition(x, y);
4024}
4025
4026void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4027 BitSet32 spotIdBits, int32_t displayId) {
4028 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4029
4030 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4031 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4032 float x = spotCoords[index].getX();
4033 float y = spotCoords[index].getY();
4034 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4035
4036 if (isPerWindowInputRotationEnabled()) {
4037 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4038 // coordinate space.
4039 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4040 }
4041
4042 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4043 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4044 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4045 }
4046
4047 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4048}
4049
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004050} // namespace android