blob: ac5f6b652be54926e5ce0854ec89ed5fc047a149 [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
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700473 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
474 String8 orientationString;
475 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientation"),
476 orientationString)) {
477 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
478 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
479 } else if (orientationString == "ORIENTATION_90") {
480 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
481 } else if (orientationString == "ORIENTATION_180") {
482 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
483 } else if (orientationString == "ORIENTATION_270") {
484 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
485 } else if (orientationString != "ORIENTATION_0") {
486 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.string());
487 }
488 }
489
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700490 mParameters.hasAssociatedDisplay = false;
491 mParameters.associatedDisplayIsExternal = false;
492 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100493 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
494 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700495 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100496 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800497 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700498 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800499 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
500 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700501 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
502 }
503 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800504 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700505 mParameters.hasAssociatedDisplay = true;
506 }
507
508 // Initial downs on external touch devices should wake the device.
509 // Normally we don't do this for internal touch screens to prevent them from waking
510 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800511 mParameters.wake = getDeviceContext().isExternal();
512 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700513}
514
515void TouchInputMapper::dumpParameters(std::string& dump) {
516 dump += INDENT3 "Parameters:\n";
517
Chris Yea03dd232020-09-08 19:21:09 -0700518 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700519
Chris Yea03dd232020-09-08 19:21:09 -0700520 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700521
522 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
523 "displayId='%s'\n",
524 toString(mParameters.hasAssociatedDisplay),
525 toString(mParameters.associatedDisplayIsExternal),
526 mParameters.uniqueDisplayId.c_str());
527 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700528 dump += INDENT4 "Orientation: " + NamedEnum::string(mParameters.orientation) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700529}
530
531void TouchInputMapper::configureRawPointerAxes() {
532 mRawPointerAxes.clear();
533}
534
535void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
536 dump += INDENT3 "Raw Touch Axes:\n";
537 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
538 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
549 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
550}
551
552bool TouchInputMapper::hasExternalStylus() const {
553 return mExternalStylusConnected;
554}
555
556/**
557 * Determine which DisplayViewport to use.
558 * 1. If display port is specified, return the matching viewport. If matching viewport not
559 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800560 * 2. Always use the suggested viewport from WindowManagerService for pointers.
561 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700562 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800563 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 */
565std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800566 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800567 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700568 if (displayPort) {
569 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800570 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700571 }
572
Michael Wright227c5542020-07-02 18:30:52 +0100573 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800574 std::optional<DisplayViewport> viewport =
575 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
576 if (viewport) {
577 return viewport;
578 } else {
579 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
580 mConfig.defaultPointerDisplayId);
581 }
582 }
583
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700584 // Check if uniqueDisplayId is specified in idc file.
585 if (!mParameters.uniqueDisplayId.empty()) {
586 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
587 }
588
589 ViewportType viewportTypeToUse;
590 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100591 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700592 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100593 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700594 }
595
596 std::optional<DisplayViewport> viewport =
597 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100598 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700599 ALOGW("Input device %s should be associated with external display, "
600 "fallback to internal one for the external viewport is not found.",
601 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100602 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700603 }
604
605 return viewport;
606 }
607
608 // No associated display, return a non-display viewport.
609 DisplayViewport newViewport;
610 // Raw width and height in the natural orientation.
611 int32_t rawWidth = mRawPointerAxes.getRawWidth();
612 int32_t rawHeight = mRawPointerAxes.getRawHeight();
613 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
614 return std::make_optional(newViewport);
615}
616
617void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100618 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700619
620 resolveExternalStylusPresence();
621
622 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100623 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000624 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700625 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100626 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700627 if (hasStylus()) {
628 mSource |= AINPUT_SOURCE_STYLUS;
629 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800630 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700631 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100632 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700633 if (hasStylus()) {
634 mSource |= AINPUT_SOURCE_STYLUS;
635 }
636 if (hasExternalStylus()) {
637 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
638 }
Michael Wright227c5542020-07-02 18:30:52 +0100639 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700640 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100641 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700642 } else {
643 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100644 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700645 }
646
647 // Ensure we have valid X and Y axes.
648 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
649 ALOGW("Touch device '%s' did not report support for X or Y axis! "
650 "The device will be inoperable.",
651 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100652 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700653 return;
654 }
655
656 // Get associated display dimensions.
657 std::optional<DisplayViewport> newViewport = findViewport();
658 if (!newViewport) {
659 ALOGI("Touch device '%s' could not query the properties of its associated "
660 "display. The device will be inoperable until the display size "
661 "becomes available.",
662 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100663 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700664 return;
665 }
666
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000667 if (!newViewport->isActive) {
668 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
669 getDeviceName().c_str(), getDeviceId());
670 mDeviceMode = DeviceMode::DISABLED;
671 return;
672 }
673
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700674 // Raw width and height in the natural orientation.
675 int32_t rawWidth = mRawPointerAxes.getRawWidth();
676 int32_t rawHeight = mRawPointerAxes.getRawHeight();
677
678 bool viewportChanged = mViewport != *newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700679 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700680 if (viewportChanged) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700681 bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700682 mViewport = *newViewport;
683
Michael Wright227c5542020-07-02 18:30:52 +0100684 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700685 // Convert rotated viewport to natural surface coordinates.
686 int32_t naturalLogicalWidth, naturalLogicalHeight;
687 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
688 int32_t naturalPhysicalLeft, naturalPhysicalTop;
689 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700690
691 // Apply the inverse of the input device orientation so that the surface is configured
692 // in the same orientation as the device. The input device orientation will be
693 // re-applied to mSurfaceOrientation.
694 const int32_t naturalSurfaceOrientation =
695 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
696 switch (naturalSurfaceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700697 case DISPLAY_ORIENTATION_90:
698 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
699 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
700 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
701 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800702 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700703 naturalPhysicalTop = mViewport.physicalLeft;
704 naturalDeviceWidth = mViewport.deviceHeight;
705 naturalDeviceHeight = mViewport.deviceWidth;
706 break;
707 case DISPLAY_ORIENTATION_180:
708 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
709 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
710 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
711 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
712 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
713 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
714 naturalDeviceWidth = mViewport.deviceWidth;
715 naturalDeviceHeight = mViewport.deviceHeight;
716 break;
717 case DISPLAY_ORIENTATION_270:
718 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
719 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
720 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
721 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
722 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800723 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700724 naturalDeviceWidth = mViewport.deviceHeight;
725 naturalDeviceHeight = mViewport.deviceWidth;
726 break;
727 case DISPLAY_ORIENTATION_0:
728 default:
729 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
730 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
731 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
732 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
733 naturalPhysicalLeft = mViewport.physicalLeft;
734 naturalPhysicalTop = mViewport.physicalTop;
735 naturalDeviceWidth = mViewport.deviceWidth;
736 naturalDeviceHeight = mViewport.deviceHeight;
737 break;
738 }
739
740 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
741 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
742 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
743 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
744 }
745
746 mPhysicalWidth = naturalPhysicalWidth;
747 mPhysicalHeight = naturalPhysicalHeight;
748 mPhysicalLeft = naturalPhysicalLeft;
749 mPhysicalTop = naturalPhysicalTop;
750
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700751 const int32_t oldSurfaceWidth = mRawSurfaceWidth;
752 const int32_t oldSurfaceHeight = mRawSurfaceHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800753 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
754 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700755 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
756 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800757 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
758 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700759
Prabir Pradhand7482e72021-03-09 13:54:55 -0800760 if (isPerWindowInputRotationEnabled()) {
761 // When per-window input rotation is enabled, InputReader works in the un-rotated
762 // coordinate space, so we don't need to do anything if the device is already
763 // orientation-aware. If the device is not orientation-aware, then we need to apply
764 // the inverse rotation of the display so that when the display rotation is applied
765 // later as a part of the per-window transform, we get the expected screen
766 // coordinates.
767 mSurfaceOrientation = mParameters.orientationAware
768 ? DISPLAY_ORIENTATION_0
769 : getInverseRotation(mViewport.orientation);
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700770 // For orientation-aware devices that work in the un-rotated coordinate space, the
771 // viewport update should be skipped if it is only a change in the orientation.
772 skipViewportUpdate = mParameters.orientationAware &&
773 mRawSurfaceWidth == oldSurfaceWidth &&
774 mRawSurfaceHeight == oldSurfaceHeight && viewportOrientationChanged;
Prabir Pradhand7482e72021-03-09 13:54:55 -0800775 } else {
776 mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation
777 : DISPLAY_ORIENTATION_0;
778 }
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700779
780 // Apply the input device orientation for the device.
781 mSurfaceOrientation =
782 (mSurfaceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700783 } else {
784 mPhysicalWidth = rawWidth;
785 mPhysicalHeight = rawHeight;
786 mPhysicalLeft = 0;
787 mPhysicalTop = 0;
788
Arthur Hung4197f6b2020-03-16 15:39:59 +0800789 mRawSurfaceWidth = rawWidth;
790 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700791 mSurfaceLeft = 0;
792 mSurfaceTop = 0;
793 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
794 }
795 }
796
797 // If moving between pointer modes, need to reset some state.
798 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
799 if (deviceModeChanged) {
800 mOrientedRanges.clear();
801 }
802
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800803 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
804 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100805 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800806 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000807 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
808 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800809 if (mPointerController == nullptr) {
810 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700811 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000812 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800813 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
814 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700815 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100816 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700817 }
818
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700819 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700820 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
821 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800822 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700823 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
824
825 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800826 mXScale = float(mRawSurfaceWidth) / rawWidth;
827 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700828 mXTranslate = -mSurfaceLeft;
829 mYTranslate = -mSurfaceTop;
830 mXPrecision = 1.0f / mXScale;
831 mYPrecision = 1.0f / mYScale;
832
833 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
834 mOrientedRanges.x.source = mSource;
835 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
836 mOrientedRanges.y.source = mSource;
837
838 configureVirtualKeys();
839
840 // Scale factor for terms that are not oriented in a particular axis.
841 // If the pixels are square then xScale == yScale otherwise we fake it
842 // by choosing an average.
843 mGeometricScale = avg(mXScale, mYScale);
844
845 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800846 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700847
848 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100849 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700850 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
851 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
852 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
853 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
854 } else {
855 mSizeScale = 0.0f;
856 }
857
858 mOrientedRanges.haveTouchSize = true;
859 mOrientedRanges.haveToolSize = true;
860 mOrientedRanges.haveSize = true;
861
862 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
863 mOrientedRanges.touchMajor.source = mSource;
864 mOrientedRanges.touchMajor.min = 0;
865 mOrientedRanges.touchMajor.max = diagonalSize;
866 mOrientedRanges.touchMajor.flat = 0;
867 mOrientedRanges.touchMajor.fuzz = 0;
868 mOrientedRanges.touchMajor.resolution = 0;
869
870 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
871 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
872
873 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
874 mOrientedRanges.toolMajor.source = mSource;
875 mOrientedRanges.toolMajor.min = 0;
876 mOrientedRanges.toolMajor.max = diagonalSize;
877 mOrientedRanges.toolMajor.flat = 0;
878 mOrientedRanges.toolMajor.fuzz = 0;
879 mOrientedRanges.toolMajor.resolution = 0;
880
881 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
882 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
883
884 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
885 mOrientedRanges.size.source = mSource;
886 mOrientedRanges.size.min = 0;
887 mOrientedRanges.size.max = 1.0;
888 mOrientedRanges.size.flat = 0;
889 mOrientedRanges.size.fuzz = 0;
890 mOrientedRanges.size.resolution = 0;
891 } else {
892 mSizeScale = 0.0f;
893 }
894
895 // Pressure factors.
896 mPressureScale = 0;
897 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100898 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
899 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700900 if (mCalibration.havePressureScale) {
901 mPressureScale = mCalibration.pressureScale;
902 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
903 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
904 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
905 }
906 }
907
908 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
909 mOrientedRanges.pressure.source = mSource;
910 mOrientedRanges.pressure.min = 0;
911 mOrientedRanges.pressure.max = pressureMax;
912 mOrientedRanges.pressure.flat = 0;
913 mOrientedRanges.pressure.fuzz = 0;
914 mOrientedRanges.pressure.resolution = 0;
915
916 // Tilt
917 mTiltXCenter = 0;
918 mTiltXScale = 0;
919 mTiltYCenter = 0;
920 mTiltYScale = 0;
921 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
922 if (mHaveTilt) {
923 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
924 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
925 mTiltXScale = M_PI / 180;
926 mTiltYScale = M_PI / 180;
927
Tatsunosuke Tobita35e05532021-06-30 14:49:32 +0900928 if (mRawPointerAxes.tiltX.resolution) {
929 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
930 }
931 if (mRawPointerAxes.tiltY.resolution) {
932 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
933 }
934
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700935 mOrientedRanges.haveTilt = true;
936
937 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
938 mOrientedRanges.tilt.source = mSource;
939 mOrientedRanges.tilt.min = 0;
940 mOrientedRanges.tilt.max = M_PI_2;
941 mOrientedRanges.tilt.flat = 0;
942 mOrientedRanges.tilt.fuzz = 0;
943 mOrientedRanges.tilt.resolution = 0;
944 }
945
946 // Orientation
947 mOrientationScale = 0;
948 if (mHaveTilt) {
949 mOrientedRanges.haveOrientation = true;
950
951 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
952 mOrientedRanges.orientation.source = mSource;
953 mOrientedRanges.orientation.min = -M_PI;
954 mOrientedRanges.orientation.max = M_PI;
955 mOrientedRanges.orientation.flat = 0;
956 mOrientedRanges.orientation.fuzz = 0;
957 mOrientedRanges.orientation.resolution = 0;
958 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100959 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700960 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100961 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700962 if (mRawPointerAxes.orientation.valid) {
963 if (mRawPointerAxes.orientation.maxValue > 0) {
964 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
965 } else if (mRawPointerAxes.orientation.minValue < 0) {
966 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
967 } else {
968 mOrientationScale = 0;
969 }
970 }
971 }
972
973 mOrientedRanges.haveOrientation = true;
974
975 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
976 mOrientedRanges.orientation.source = mSource;
977 mOrientedRanges.orientation.min = -M_PI_2;
978 mOrientedRanges.orientation.max = M_PI_2;
979 mOrientedRanges.orientation.flat = 0;
980 mOrientedRanges.orientation.fuzz = 0;
981 mOrientedRanges.orientation.resolution = 0;
982 }
983
984 // Distance
985 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100986 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
987 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700988 if (mCalibration.haveDistanceScale) {
989 mDistanceScale = mCalibration.distanceScale;
990 } else {
991 mDistanceScale = 1.0f;
992 }
993 }
994
995 mOrientedRanges.haveDistance = true;
996
997 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
998 mOrientedRanges.distance.source = mSource;
999 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
1000 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
1001 mOrientedRanges.distance.flat = 0;
1002 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
1003 mOrientedRanges.distance.resolution = 0;
1004 }
1005
1006 // Compute oriented precision, scales and ranges.
1007 // Note that the maximum value reported is an inclusive maximum value so it is one
1008 // unit less than the total width or height of surface.
1009 switch (mSurfaceOrientation) {
1010 case DISPLAY_ORIENTATION_90:
1011 case DISPLAY_ORIENTATION_270:
1012 mOrientedXPrecision = mYPrecision;
1013 mOrientedYPrecision = mXPrecision;
1014
1015 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001016 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001017 mOrientedRanges.x.flat = 0;
1018 mOrientedRanges.x.fuzz = 0;
1019 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
1020
1021 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001022 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023 mOrientedRanges.y.flat = 0;
1024 mOrientedRanges.y.fuzz = 0;
1025 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
1026 break;
1027
1028 default:
1029 mOrientedXPrecision = mXPrecision;
1030 mOrientedYPrecision = mYPrecision;
1031
1032 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001033 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001034 mOrientedRanges.x.flat = 0;
1035 mOrientedRanges.x.fuzz = 0;
1036 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1037
1038 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001039 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001040 mOrientedRanges.y.flat = 0;
1041 mOrientedRanges.y.fuzz = 0;
1042 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1043 break;
1044 }
1045
1046 // Location
1047 updateAffineTransformation();
1048
Michael Wright227c5542020-07-02 18:30:52 +01001049 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001050 // Compute pointer gesture detection parameters.
1051 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001052 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053
1054 // Scale movements such that one whole swipe of the touch pad covers a
1055 // given area relative to the diagonal size of the display when no acceleration
1056 // is applied.
1057 // Assume that the touch pad has a square aspect ratio such that movements in
1058 // X and Y of the same number of raw units cover the same physical distance.
1059 mPointerXMovementScale =
1060 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1061 mPointerYMovementScale = mPointerXMovementScale;
1062
1063 // Scale zooms to cover a smaller range of the display than movements do.
1064 // This value determines the area around the pointer that is affected by freeform
1065 // pointer gestures.
1066 mPointerXZoomScale =
1067 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1068 mPointerYZoomScale = mPointerXZoomScale;
1069
1070 // Max width between pointers to detect a swipe gesture is more than some fraction
1071 // of the diagonal axis of the touch pad. Touches that are wider than this are
1072 // translated into freeform gestures.
1073 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1074
1075 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001076 const nsecs_t readTime = when; // synthetic event
1077 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001078 }
1079
1080 // Inform the dispatcher about the changes.
1081 *outResetNeeded = true;
1082 bumpGeneration();
1083 }
1084}
1085
1086void TouchInputMapper::dumpSurface(std::string& dump) {
1087 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001088 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1089 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001090 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1091 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001092 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1093 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001094 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1095 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1096 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1097 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1098 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1099}
1100
1101void TouchInputMapper::configureVirtualKeys() {
1102 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001103 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104
1105 mVirtualKeys.clear();
1106
1107 if (virtualKeyDefinitions.size() == 0) {
1108 return;
1109 }
1110
1111 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1112 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1113 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1114 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1115
1116 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1117 VirtualKey virtualKey;
1118
1119 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1120 int32_t keyCode;
1121 int32_t dummyKeyMetaState;
1122 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001123 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1124 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001125 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1126 continue; // drop the key
1127 }
1128
1129 virtualKey.keyCode = keyCode;
1130 virtualKey.flags = flags;
1131
1132 // convert the key definition's display coordinates into touch coordinates for a hit box
1133 int32_t halfWidth = virtualKeyDefinition.width / 2;
1134 int32_t halfHeight = virtualKeyDefinition.height / 2;
1135
1136 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001137 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138 touchScreenLeft;
1139 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001140 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001142 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1143 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001145 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1146 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 touchScreenTop;
1148 mVirtualKeys.push_back(virtualKey);
1149 }
1150}
1151
1152void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1153 if (!mVirtualKeys.empty()) {
1154 dump += INDENT3 "Virtual Keys:\n";
1155
1156 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1157 const VirtualKey& virtualKey = mVirtualKeys[i];
1158 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1159 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1160 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1161 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1162 }
1163 }
1164}
1165
1166void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001167 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 Calibration& out = mCalibration;
1169
1170 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 String8 sizeCalibrationString;
1173 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1174 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 } else if (sizeCalibrationString != "default") {
1185 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1186 }
1187 }
1188
1189 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1190 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1191 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1192
1193 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001194 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 String8 pressureCalibrationString;
1196 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1197 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001198 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 } else if (pressureCalibrationString != "default") {
1204 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1205 pressureCalibrationString.string());
1206 }
1207 }
1208
1209 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1210
1211 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 String8 orientationCalibrationString;
1214 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1215 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001220 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 } else if (orientationCalibrationString != "default") {
1222 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1223 orientationCalibrationString.string());
1224 }
1225 }
1226
1227 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001228 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 String8 distanceCalibrationString;
1230 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1231 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001232 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001234 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235 } else if (distanceCalibrationString != "default") {
1236 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1237 distanceCalibrationString.string());
1238 }
1239 }
1240
1241 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1242
Michael Wright227c5542020-07-02 18:30:52 +01001243 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 String8 coverageCalibrationString;
1245 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1246 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001247 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001249 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 } else if (coverageCalibrationString != "default") {
1251 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1252 coverageCalibrationString.string());
1253 }
1254 }
1255}
1256
1257void TouchInputMapper::resolveCalibration() {
1258 // Size
1259 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001260 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1261 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001264 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 }
1266
1267 // Pressure
1268 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001269 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1270 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001273 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274 }
1275
1276 // Orientation
1277 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001278 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1279 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 }
1281 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001282 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 }
1284
1285 // Distance
1286 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001287 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1288 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 }
1290 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001291 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 }
1293
1294 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001295 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1296 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 }
1298}
1299
1300void TouchInputMapper::dumpCalibration(std::string& dump) {
1301 dump += INDENT3 "Calibration:\n";
1302
1303 // Size
1304 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001305 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 dump += INDENT4 "touch.size.calibration: none\n";
1307 break;
Michael Wright227c5542020-07-02 18:30:52 +01001308 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 dump += INDENT4 "touch.size.calibration: geometric\n";
1310 break;
Michael Wright227c5542020-07-02 18:30:52 +01001311 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.size.calibration: diameter\n";
1313 break;
Michael Wright227c5542020-07-02 18:30:52 +01001314 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.size.calibration: box\n";
1316 break;
Michael Wright227c5542020-07-02 18:30:52 +01001317 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.size.calibration: area\n";
1319 break;
1320 default:
1321 ALOG_ASSERT(false);
1322 }
1323
1324 if (mCalibration.haveSizeScale) {
1325 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1326 }
1327
1328 if (mCalibration.haveSizeBias) {
1329 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1330 }
1331
1332 if (mCalibration.haveSizeIsSummed) {
1333 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1334 toString(mCalibration.sizeIsSummed));
1335 }
1336
1337 // Pressure
1338 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001339 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340 dump += INDENT4 "touch.pressure.calibration: none\n";
1341 break;
Michael Wright227c5542020-07-02 18:30:52 +01001342 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 dump += INDENT4 "touch.pressure.calibration: physical\n";
1344 break;
Michael Wright227c5542020-07-02 18:30:52 +01001345 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1347 break;
1348 default:
1349 ALOG_ASSERT(false);
1350 }
1351
1352 if (mCalibration.havePressureScale) {
1353 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1354 }
1355
1356 // Orientation
1357 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001358 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001359 dump += INDENT4 "touch.orientation.calibration: none\n";
1360 break;
Michael Wright227c5542020-07-02 18:30:52 +01001361 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001362 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1363 break;
Michael Wright227c5542020-07-02 18:30:52 +01001364 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001365 dump += INDENT4 "touch.orientation.calibration: vector\n";
1366 break;
1367 default:
1368 ALOG_ASSERT(false);
1369 }
1370
1371 // Distance
1372 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001373 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374 dump += INDENT4 "touch.distance.calibration: none\n";
1375 break;
Michael Wright227c5542020-07-02 18:30:52 +01001376 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001377 dump += INDENT4 "touch.distance.calibration: scaled\n";
1378 break;
1379 default:
1380 ALOG_ASSERT(false);
1381 }
1382
1383 if (mCalibration.haveDistanceScale) {
1384 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1385 }
1386
1387 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001388 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001389 dump += INDENT4 "touch.coverage.calibration: none\n";
1390 break;
Michael Wright227c5542020-07-02 18:30:52 +01001391 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001392 dump += INDENT4 "touch.coverage.calibration: box\n";
1393 break;
1394 default:
1395 ALOG_ASSERT(false);
1396 }
1397}
1398
1399void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1400 dump += INDENT3 "Affine Transformation:\n";
1401
1402 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1403 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1404 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1405 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1406 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1407 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1408}
1409
1410void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001411 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001412 mSurfaceOrientation);
1413}
1414
1415void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001416 mCursorButtonAccumulator.reset(getDeviceContext());
1417 mCursorScrollAccumulator.reset(getDeviceContext());
1418 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001419
1420 mPointerVelocityControl.reset();
1421 mWheelXVelocityControl.reset();
1422 mWheelYVelocityControl.reset();
1423
1424 mRawStatesPending.clear();
1425 mCurrentRawState.clear();
1426 mCurrentCookedState.clear();
1427 mLastRawState.clear();
1428 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001429 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001430 mSentHoverEnter = false;
1431 mHavePointerIds = false;
1432 mCurrentMotionAborted = false;
1433 mDownTime = 0;
1434
1435 mCurrentVirtualKey.down = false;
1436
1437 mPointerGesture.reset();
1438 mPointerSimple.reset();
1439 resetExternalStylus();
1440
1441 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001442 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001443 mPointerController->clearSpots();
1444 }
1445
1446 InputMapper::reset(when);
1447}
1448
1449void TouchInputMapper::resetExternalStylus() {
1450 mExternalStylusState.clear();
1451 mExternalStylusId = -1;
1452 mExternalStylusFusionTimeout = LLONG_MAX;
1453 mExternalStylusDataPending = false;
1454}
1455
1456void TouchInputMapper::clearStylusDataPendingFlags() {
1457 mExternalStylusDataPending = false;
1458 mExternalStylusFusionTimeout = LLONG_MAX;
1459}
1460
1461void TouchInputMapper::process(const RawEvent* rawEvent) {
1462 mCursorButtonAccumulator.process(rawEvent);
1463 mCursorScrollAccumulator.process(rawEvent);
1464 mTouchButtonAccumulator.process(rawEvent);
1465
1466 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001467 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001468 }
1469}
1470
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001471void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001472 // Push a new state.
1473 mRawStatesPending.emplace_back();
1474
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001475 RawState& next = mRawStatesPending.back();
1476 next.clear();
1477 next.when = when;
1478 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479
1480 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001481 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001482 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1483
1484 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001485 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1486 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001487 mCursorScrollAccumulator.finishSync();
1488
1489 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001490 syncTouch(when, &next);
1491
1492 // The last RawState is the actually second to last, since we just added a new state
1493 const RawState& last =
1494 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001495
1496 // Assign pointer ids.
1497 if (!mHavePointerIds) {
1498 assignPointerIds(last, next);
1499 }
1500
1501#if DEBUG_RAW_EVENTS
1502 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001503 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001504 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1505 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1506 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1507 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001508#endif
1509
Arthur Hung9ad18942021-06-19 02:04:46 +00001510 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1511 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1512 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1513 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1514 next.rawPointerData.hoveringIdBits.value);
1515 }
1516
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 processRawTouches(false /*timeout*/);
1518}
1519
1520void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001521 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001523 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001524 mCurrentCookedState.clear();
1525 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001526 return;
1527 }
1528
1529 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1530 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1531 // touching the current state will only observe the events that have been dispatched to the
1532 // rest of the pipeline.
1533 const size_t N = mRawStatesPending.size();
1534 size_t count;
1535 for (count = 0; count < N; count++) {
1536 const RawState& next = mRawStatesPending[count];
1537
1538 // A failure to assign the stylus id means that we're waiting on stylus data
1539 // and so should defer the rest of the pipeline.
1540 if (assignExternalStylusId(next, timeout)) {
1541 break;
1542 }
1543
1544 // All ready to go.
1545 clearStylusDataPendingFlags();
1546 mCurrentRawState.copyFrom(next);
1547 if (mCurrentRawState.when < mLastRawState.when) {
1548 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001549 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001551 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001552 }
1553 if (count != 0) {
1554 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1555 }
1556
1557 if (mExternalStylusDataPending) {
1558 if (timeout) {
1559 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1560 clearStylusDataPendingFlags();
1561 mCurrentRawState.copyFrom(mLastRawState);
1562#if DEBUG_STYLUS_FUSION
1563 ALOGD("Timeout expired, synthesizing event with new stylus data");
1564#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001565 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1566 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001567 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1568 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1569 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1570 }
1571 }
1572}
1573
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001574void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001575 // Always start with a clean state.
1576 mCurrentCookedState.clear();
1577
1578 // Apply stylus buttons to current raw state.
1579 applyExternalStylusButtonState(when);
1580
1581 // Handle policy on initial down or hover events.
1582 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1583 mCurrentRawState.rawPointerData.pointerCount != 0;
1584
1585 uint32_t policyFlags = 0;
1586 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1587 if (initialDown || buttonsPressed) {
1588 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001589 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590 getContext()->fadePointer();
1591 }
1592
1593 if (mParameters.wake) {
1594 policyFlags |= POLICY_FLAG_WAKE;
1595 }
1596 }
1597
1598 // Consume raw off-screen touches before cooking pointer data.
1599 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001600 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001601 mCurrentRawState.rawPointerData.clear();
1602 }
1603
1604 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1605 // with cooked pointer data that has the same ids and indices as the raw data.
1606 // The following code can use either the raw or cooked data, as needed.
1607 cookPointerData();
1608
1609 // Apply stylus pressure to current cooked state.
1610 applyExternalStylusTouchState(when);
1611
1612 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001613 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1614 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 mCurrentCookedState.buttonState);
1616
1617 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001618 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001619 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1620 uint32_t id = idBits.clearFirstMarkedBit();
1621 const RawPointerData::Pointer& pointer =
1622 mCurrentRawState.rawPointerData.pointerForId(id);
1623 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1624 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1625 mCurrentCookedState.stylusIdBits.markBit(id);
1626 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1627 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1628 mCurrentCookedState.fingerIdBits.markBit(id);
1629 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1630 mCurrentCookedState.mouseIdBits.markBit(id);
1631 }
1632 }
1633 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1634 uint32_t id = idBits.clearFirstMarkedBit();
1635 const RawPointerData::Pointer& pointer =
1636 mCurrentRawState.rawPointerData.pointerForId(id);
1637 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1638 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1639 mCurrentCookedState.stylusIdBits.markBit(id);
1640 }
1641 }
1642
1643 // Stylus takes precedence over all tools, then mouse, then finger.
1644 PointerUsage pointerUsage = mPointerUsage;
1645 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1646 mCurrentCookedState.mouseIdBits.clear();
1647 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001648 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001649 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1650 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001651 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001652 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1653 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001654 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001655 }
1656
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001657 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001658 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001659 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001660
1661 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001662 dispatchButtonRelease(when, readTime, policyFlags);
1663 dispatchHoverExit(when, readTime, policyFlags);
1664 dispatchTouches(when, readTime, policyFlags);
1665 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1666 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001667 }
1668
1669 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1670 mCurrentMotionAborted = false;
1671 }
1672 }
1673
1674 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001675 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001676 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1677 mCurrentCookedState.buttonState);
1678
1679 // Clear some transient state.
1680 mCurrentRawState.rawVScroll = 0;
1681 mCurrentRawState.rawHScroll = 0;
1682
1683 // Copy current touch to last touch in preparation for the next cycle.
1684 mLastRawState.copyFrom(mCurrentRawState);
1685 mLastCookedState.copyFrom(mCurrentCookedState);
1686}
1687
Garfield Tanc734e4f2021-01-15 20:01:39 -08001688void TouchInputMapper::updateTouchSpots() {
1689 if (!mConfig.showTouches || mPointerController == nullptr) {
1690 return;
1691 }
1692
1693 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1694 // clear touch spots.
1695 if (mDeviceMode != DeviceMode::DIRECT &&
1696 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1697 return;
1698 }
1699
1700 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1701 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1702
1703 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001704 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1705 mCurrentCookedState.cookedPointerData.idToIndex,
1706 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001707}
1708
1709bool TouchInputMapper::isTouchScreen() {
1710 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1711 mParameters.hasAssociatedDisplay;
1712}
1713
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001715 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001716 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1717 }
1718}
1719
1720void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1721 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1722 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1723
1724 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1725 float pressure = mExternalStylusState.pressure;
1726 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1727 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1728 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1729 }
1730 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1731 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1732
1733 PointerProperties& properties =
1734 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1735 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1736 properties.toolType = mExternalStylusState.toolType;
1737 }
1738 }
1739}
1740
1741bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001742 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001743 return false;
1744 }
1745
1746 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1747 state.rawPointerData.pointerCount != 0;
1748 if (initialDown) {
1749 if (mExternalStylusState.pressure != 0.0f) {
1750#if DEBUG_STYLUS_FUSION
1751 ALOGD("Have both stylus and touch data, beginning fusion");
1752#endif
1753 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1754 } else if (timeout) {
1755#if DEBUG_STYLUS_FUSION
1756 ALOGD("Timeout expired, assuming touch is not a stylus.");
1757#endif
1758 resetExternalStylus();
1759 } else {
1760 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1761 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1762 }
1763#if DEBUG_STYLUS_FUSION
1764 ALOGD("No stylus data but stylus is connected, requesting timeout "
1765 "(%" PRId64 "ms)",
1766 mExternalStylusFusionTimeout);
1767#endif
1768 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1769 return true;
1770 }
1771 }
1772
1773 // Check if the stylus pointer has gone up.
1774 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1775#if DEBUG_STYLUS_FUSION
1776 ALOGD("Stylus pointer is going up");
1777#endif
1778 mExternalStylusId = -1;
1779 }
1780
1781 return false;
1782}
1783
1784void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001785 if (mDeviceMode == DeviceMode::POINTER) {
1786 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001787 // Since this is a synthetic event, we can consider its latency to be zero
1788 const nsecs_t readTime = when;
1789 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001790 }
Michael Wright227c5542020-07-02 18:30:52 +01001791 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792 if (mExternalStylusFusionTimeout < when) {
1793 processRawTouches(true /*timeout*/);
1794 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1795 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1796 }
1797 }
1798}
1799
1800void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1801 mExternalStylusState.copyFrom(state);
1802 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1803 // We're either in the middle of a fused stream of data or we're waiting on data before
1804 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1805 // data.
1806 mExternalStylusDataPending = true;
1807 processRawTouches(false /*timeout*/);
1808 }
1809}
1810
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001811bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001812 // Check for release of a virtual key.
1813 if (mCurrentVirtualKey.down) {
1814 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1815 // Pointer went up while virtual key was down.
1816 mCurrentVirtualKey.down = false;
1817 if (!mCurrentVirtualKey.ignored) {
1818#if DEBUG_VIRTUAL_KEYS
1819 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1820 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1821#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001822 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001823 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1824 }
1825 return true;
1826 }
1827
1828 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1829 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1830 const RawPointerData::Pointer& pointer =
1831 mCurrentRawState.rawPointerData.pointerForId(id);
1832 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1833 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1834 // Pointer is still within the space of the virtual key.
1835 return true;
1836 }
1837 }
1838
1839 // Pointer left virtual key area or another pointer also went down.
1840 // Send key cancellation but do not consume the touch yet.
1841 // This is useful when the user swipes through from the virtual key area
1842 // into the main display surface.
1843 mCurrentVirtualKey.down = false;
1844 if (!mCurrentVirtualKey.ignored) {
1845#if DEBUG_VIRTUAL_KEYS
1846 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1847 mCurrentVirtualKey.scanCode);
1848#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001849 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001850 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1851 AKEY_EVENT_FLAG_CANCELED);
1852 }
1853 }
1854
1855 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1856 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1857 // Pointer just went down. Check for virtual key press or off-screen touches.
1858 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1859 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001860 // Exclude unscaled device for inside surface checking.
1861 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001862 // If exactly one pointer went down, check for virtual key hit.
1863 // Otherwise we will drop the entire stroke.
1864 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1865 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1866 if (virtualKey) {
1867 mCurrentVirtualKey.down = true;
1868 mCurrentVirtualKey.downTime = when;
1869 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1870 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1871 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001872 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1873 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001874
1875 if (!mCurrentVirtualKey.ignored) {
1876#if DEBUG_VIRTUAL_KEYS
1877 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1878 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1879#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001880 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001881 AKEY_EVENT_FLAG_FROM_SYSTEM |
1882 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1883 }
1884 }
1885 }
1886 return true;
1887 }
1888 }
1889
1890 // Disable all virtual key touches that happen within a short time interval of the
1891 // most recent touch within the screen area. The idea is to filter out stray
1892 // virtual key presses when interacting with the touch screen.
1893 //
1894 // Problems we're trying to solve:
1895 //
1896 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1897 // virtual key area that is implemented by a separate touch panel and accidentally
1898 // triggers a virtual key.
1899 //
1900 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1901 // area and accidentally triggers a virtual key. This often happens when virtual keys
1902 // are layed out below the screen near to where the on screen keyboard's space bar
1903 // is displayed.
1904 if (mConfig.virtualKeyQuietTime > 0 &&
1905 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001906 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907 }
1908 return false;
1909}
1910
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001911void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001912 int32_t keyEventAction, int32_t keyEventFlags) {
1913 int32_t keyCode = mCurrentVirtualKey.keyCode;
1914 int32_t scanCode = mCurrentVirtualKey.scanCode;
1915 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001916 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001917 policyFlags |= POLICY_FLAG_VIRTUAL;
1918
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001919 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1920 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1921 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001922 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001923}
1924
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001925void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1927 if (!currentIdBits.isEmpty()) {
1928 int32_t metaState = getContext()->getGlobalMetaState();
1929 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001930 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1931 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001932 mCurrentCookedState.cookedPointerData.pointerProperties,
1933 mCurrentCookedState.cookedPointerData.pointerCoords,
1934 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1935 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1936 mCurrentMotionAborted = true;
1937 }
1938}
1939
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001940void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001941 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1942 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1943 int32_t metaState = getContext()->getGlobalMetaState();
1944 int32_t buttonState = mCurrentCookedState.buttonState;
1945
1946 if (currentIdBits == lastIdBits) {
1947 if (!currentIdBits.isEmpty()) {
1948 // No pointer id changes so this is a move event.
1949 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001950 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1951 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001952 mCurrentCookedState.cookedPointerData.pointerProperties,
1953 mCurrentCookedState.cookedPointerData.pointerCoords,
1954 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1955 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1956 }
1957 } else {
1958 // There may be pointers going up and pointers going down and pointers moving
1959 // all at the same time.
1960 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1961 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1962 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1963 BitSet32 dispatchedIdBits(lastIdBits.value);
1964
1965 // Update last coordinates of pointers that have moved so that we observe the new
1966 // pointer positions at the same time as other pointers that have just gone up.
1967 bool moveNeeded =
1968 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1969 mCurrentCookedState.cookedPointerData.pointerCoords,
1970 mCurrentCookedState.cookedPointerData.idToIndex,
1971 mLastCookedState.cookedPointerData.pointerProperties,
1972 mLastCookedState.cookedPointerData.pointerCoords,
1973 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1974 if (buttonState != mLastCookedState.buttonState) {
1975 moveNeeded = true;
1976 }
1977
1978 // Dispatch pointer up events.
1979 while (!upIdBits.isEmpty()) {
1980 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001981 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001982 if (isCanceled) {
1983 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1984 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001985 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001986 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001987 mLastCookedState.cookedPointerData.pointerProperties,
1988 mLastCookedState.cookedPointerData.pointerCoords,
1989 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1990 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1991 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001992 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001993 }
1994
1995 // Dispatch move events if any of the remaining pointers moved from their old locations.
1996 // Although applications receive new locations as part of individual pointer up
1997 // events, they do not generally handle them except when presented in a move event.
1998 if (moveNeeded && !moveIdBits.isEmpty()) {
1999 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002000 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
2001 metaState, buttonState, 0,
2002 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002003 mCurrentCookedState.cookedPointerData.pointerCoords,
2004 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
2005 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2006 }
2007
2008 // Dispatch pointer down events using the new pointer locations.
2009 while (!downIdBits.isEmpty()) {
2010 uint32_t downId = downIdBits.clearFirstMarkedBit();
2011 dispatchedIdBits.markBit(downId);
2012
2013 if (dispatchedIdBits.count() == 1) {
2014 // First pointer is going down. Set down time.
2015 mDownTime = when;
2016 }
2017
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002018 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2019 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002020 mCurrentCookedState.cookedPointerData.pointerProperties,
2021 mCurrentCookedState.cookedPointerData.pointerCoords,
2022 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
2023 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2024 }
2025 }
2026}
2027
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002028void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002029 if (mSentHoverEnter &&
2030 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2031 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2032 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002033 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2034 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002035 mLastCookedState.cookedPointerData.pointerProperties,
2036 mLastCookedState.cookedPointerData.pointerCoords,
2037 mLastCookedState.cookedPointerData.idToIndex,
2038 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2039 mOrientedYPrecision, mDownTime);
2040 mSentHoverEnter = false;
2041 }
2042}
2043
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002044void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2045 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002046 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2047 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2048 int32_t metaState = getContext()->getGlobalMetaState();
2049 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002050 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2051 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002052 mCurrentCookedState.cookedPointerData.pointerProperties,
2053 mCurrentCookedState.cookedPointerData.pointerCoords,
2054 mCurrentCookedState.cookedPointerData.idToIndex,
2055 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2056 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2057 mSentHoverEnter = true;
2058 }
2059
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002060 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2061 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002062 mCurrentCookedState.cookedPointerData.pointerProperties,
2063 mCurrentCookedState.cookedPointerData.pointerCoords,
2064 mCurrentCookedState.cookedPointerData.idToIndex,
2065 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2066 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2067 }
2068}
2069
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002070void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002071 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2072 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2073 const int32_t metaState = getContext()->getGlobalMetaState();
2074 int32_t buttonState = mLastCookedState.buttonState;
2075 while (!releasedButtons.isEmpty()) {
2076 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2077 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002078 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002079 actionButton, 0, metaState, buttonState, 0,
2080 mCurrentCookedState.cookedPointerData.pointerProperties,
2081 mCurrentCookedState.cookedPointerData.pointerCoords,
2082 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2083 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2084 }
2085}
2086
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002087void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002088 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2089 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2090 const int32_t metaState = getContext()->getGlobalMetaState();
2091 int32_t buttonState = mLastCookedState.buttonState;
2092 while (!pressedButtons.isEmpty()) {
2093 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2094 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002095 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2096 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002097 mCurrentCookedState.cookedPointerData.pointerProperties,
2098 mCurrentCookedState.cookedPointerData.pointerCoords,
2099 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2100 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2101 }
2102}
2103
2104const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2105 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2106 return cookedPointerData.touchingIdBits;
2107 }
2108 return cookedPointerData.hoveringIdBits;
2109}
2110
2111void TouchInputMapper::cookPointerData() {
2112 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2113
2114 mCurrentCookedState.cookedPointerData.clear();
2115 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2116 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2117 mCurrentRawState.rawPointerData.hoveringIdBits;
2118 mCurrentCookedState.cookedPointerData.touchingIdBits =
2119 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002120 mCurrentCookedState.cookedPointerData.canceledIdBits =
2121 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002122
2123 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2124 mCurrentCookedState.buttonState = 0;
2125 } else {
2126 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2127 }
2128
2129 // Walk through the the active pointers and map device coordinates onto
2130 // surface coordinates and adjust for display orientation.
2131 for (uint32_t i = 0; i < currentPointerCount; i++) {
2132 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2133
2134 // Size
2135 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2136 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002137 case Calibration::SizeCalibration::GEOMETRIC:
2138 case Calibration::SizeCalibration::DIAMETER:
2139 case Calibration::SizeCalibration::BOX:
2140 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2142 touchMajor = in.touchMajor;
2143 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2144 toolMajor = in.toolMajor;
2145 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2146 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2147 : in.touchMajor;
2148 } else if (mRawPointerAxes.touchMajor.valid) {
2149 toolMajor = touchMajor = in.touchMajor;
2150 toolMinor = touchMinor =
2151 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2152 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2153 : in.touchMajor;
2154 } else if (mRawPointerAxes.toolMajor.valid) {
2155 touchMajor = toolMajor = in.toolMajor;
2156 touchMinor = toolMinor =
2157 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2158 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2159 : in.toolMajor;
2160 } else {
2161 ALOG_ASSERT(false,
2162 "No touch or tool axes. "
2163 "Size calibration should have been resolved to NONE.");
2164 touchMajor = 0;
2165 touchMinor = 0;
2166 toolMajor = 0;
2167 toolMinor = 0;
2168 size = 0;
2169 }
2170
2171 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2172 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2173 if (touchingCount > 1) {
2174 touchMajor /= touchingCount;
2175 touchMinor /= touchingCount;
2176 toolMajor /= touchingCount;
2177 toolMinor /= touchingCount;
2178 size /= touchingCount;
2179 }
2180 }
2181
Michael Wright227c5542020-07-02 18:30:52 +01002182 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002183 touchMajor *= mGeometricScale;
2184 touchMinor *= mGeometricScale;
2185 toolMajor *= mGeometricScale;
2186 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002187 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002188 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2189 touchMinor = touchMajor;
2190 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2191 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002192 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002193 touchMinor = touchMajor;
2194 toolMinor = toolMajor;
2195 }
2196
2197 mCalibration.applySizeScaleAndBias(&touchMajor);
2198 mCalibration.applySizeScaleAndBias(&touchMinor);
2199 mCalibration.applySizeScaleAndBias(&toolMajor);
2200 mCalibration.applySizeScaleAndBias(&toolMinor);
2201 size *= mSizeScale;
2202 break;
2203 default:
2204 touchMajor = 0;
2205 touchMinor = 0;
2206 toolMajor = 0;
2207 toolMinor = 0;
2208 size = 0;
2209 break;
2210 }
2211
2212 // Pressure
2213 float pressure;
2214 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002215 case Calibration::PressureCalibration::PHYSICAL:
2216 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002217 pressure = in.pressure * mPressureScale;
2218 break;
2219 default:
2220 pressure = in.isHovering ? 0 : 1;
2221 break;
2222 }
2223
2224 // Tilt and Orientation
2225 float tilt;
2226 float orientation;
2227 if (mHaveTilt) {
2228 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2229 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2230 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2231 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2232 } else {
2233 tilt = 0;
2234
2235 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002236 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002237 orientation = in.orientation * mOrientationScale;
2238 break;
Michael Wright227c5542020-07-02 18:30:52 +01002239 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002240 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2241 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2242 if (c1 != 0 || c2 != 0) {
2243 orientation = atan2f(c1, c2) * 0.5f;
2244 float confidence = hypotf(c1, c2);
2245 float scale = 1.0f + confidence / 16.0f;
2246 touchMajor *= scale;
2247 touchMinor /= scale;
2248 toolMajor *= scale;
2249 toolMinor /= scale;
2250 } else {
2251 orientation = 0;
2252 }
2253 break;
2254 }
2255 default:
2256 orientation = 0;
2257 }
2258 }
2259
2260 // Distance
2261 float distance;
2262 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002263 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002264 distance = in.distance * mDistanceScale;
2265 break;
2266 default:
2267 distance = 0;
2268 }
2269
2270 // Coverage
2271 int32_t rawLeft, rawTop, rawRight, rawBottom;
2272 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002273 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002274 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2275 rawRight = in.toolMinor & 0x0000ffff;
2276 rawBottom = in.toolMajor & 0x0000ffff;
2277 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2278 break;
2279 default:
2280 rawLeft = rawTop = rawRight = rawBottom = 0;
2281 break;
2282 }
2283
2284 // Adjust X,Y coords for device calibration
2285 // TODO: Adjust coverage coords?
2286 float xTransformed = in.x, yTransformed = in.y;
2287 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002288 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002289
2290 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002291 float left, top, right, bottom;
2292
2293 switch (mSurfaceOrientation) {
2294 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002295 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2296 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2297 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2298 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2299 orientation -= M_PI_2;
2300 if (mOrientedRanges.haveOrientation &&
2301 orientation < mOrientedRanges.orientation.min) {
2302 orientation +=
2303 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2304 }
2305 break;
2306 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002307 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2308 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2309 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2310 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2311 orientation -= M_PI;
2312 if (mOrientedRanges.haveOrientation &&
2313 orientation < mOrientedRanges.orientation.min) {
2314 orientation +=
2315 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2316 }
2317 break;
2318 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002319 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2320 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2321 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2322 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2323 orientation += M_PI_2;
2324 if (mOrientedRanges.haveOrientation &&
2325 orientation > mOrientedRanges.orientation.max) {
2326 orientation -=
2327 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2328 }
2329 break;
2330 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002331 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2332 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2333 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2334 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2335 break;
2336 }
2337
2338 // Write output coords.
2339 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2340 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002341 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2342 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2344 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2345 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2346 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2347 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2348 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2349 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002350 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2352 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2353 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2354 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2355 } else {
2356 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2357 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2358 }
2359
Chris Ye364fdb52020-08-05 15:07:56 -07002360 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002361 uint32_t id = in.id;
2362 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2363 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2364 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2365 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2366 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2367 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2368 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2369 }
2370
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 // Write output properties.
2372 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 properties.clear();
2374 properties.id = id;
2375 properties.toolType = in.toolType;
2376
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002377 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002379 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 }
2381}
2382
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002383void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 PointerUsage pointerUsage) {
2385 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002386 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 mPointerUsage = pointerUsage;
2388 }
2389
2390 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002391 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002392 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393 break;
Michael Wright227c5542020-07-02 18:30:52 +01002394 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002395 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 break;
Michael Wright227c5542020-07-02 18:30:52 +01002397 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002398 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002399 break;
Michael Wright227c5542020-07-02 18:30:52 +01002400 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002401 break;
2402 }
2403}
2404
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002405void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002407 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002408 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 break;
Michael Wright227c5542020-07-02 18:30:52 +01002410 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002411 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002412 break;
Michael Wright227c5542020-07-02 18:30:52 +01002413 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002414 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 break;
Michael Wright227c5542020-07-02 18:30:52 +01002416 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 break;
2418 }
2419
Michael Wright227c5542020-07-02 18:30:52 +01002420 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002421}
2422
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002423void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2424 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 // Update current gesture coordinates.
2426 bool cancelPreviousGesture, finishPreviousGesture;
2427 bool sendEvents =
2428 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2429 if (!sendEvents) {
2430 return;
2431 }
2432 if (finishPreviousGesture) {
2433 cancelPreviousGesture = false;
2434 }
2435
2436 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002437 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002438 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002439 if (finishPreviousGesture || cancelPreviousGesture) {
2440 mPointerController->clearSpots();
2441 }
2442
Michael Wright227c5542020-07-02 18:30:52 +01002443 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002444 setTouchSpots(mPointerGesture.currentGestureCoords,
2445 mPointerGesture.currentGestureIdToIndex,
2446 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002447 }
2448 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002449 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 }
2451
2452 // Show or hide the pointer if needed.
2453 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002454 case PointerGesture::Mode::NEUTRAL:
2455 case PointerGesture::Mode::QUIET:
2456 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2457 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002459 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 }
2461 break;
Michael Wright227c5542020-07-02 18:30:52 +01002462 case PointerGesture::Mode::TAP:
2463 case PointerGesture::Mode::TAP_DRAG:
2464 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2465 case PointerGesture::Mode::HOVER:
2466 case PointerGesture::Mode::PRESS:
2467 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 // Unfade the pointer when the current gesture manipulates the
2469 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002470 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002471 break;
Michael Wright227c5542020-07-02 18:30:52 +01002472 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002473 // Fade the pointer when the current gesture manipulates a different
2474 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002475 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002476 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002477 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002478 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 }
2480 break;
2481 }
2482
2483 // Send events!
2484 int32_t metaState = getContext()->getGlobalMetaState();
2485 int32_t buttonState = mCurrentCookedState.buttonState;
2486
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002487 uint32_t flags = 0;
2488
2489 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2490 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2491 }
2492
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002493 // Update last coordinates of pointers that have moved so that we observe the new
2494 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002495 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2496 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2497 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2498 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2499 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2500 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002501 bool moveNeeded = false;
2502 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2503 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2504 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2505 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2506 mPointerGesture.lastGestureIdBits.value);
2507 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2508 mPointerGesture.currentGestureCoords,
2509 mPointerGesture.currentGestureIdToIndex,
2510 mPointerGesture.lastGestureProperties,
2511 mPointerGesture.lastGestureCoords,
2512 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2513 if (buttonState != mLastCookedState.buttonState) {
2514 moveNeeded = true;
2515 }
2516 }
2517
2518 // Send motion events for all pointers that went up or were canceled.
2519 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2520 if (!dispatchedGestureIdBits.isEmpty()) {
2521 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002522 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2523 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2525 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2526 mPointerGesture.downTime);
2527
2528 dispatchedGestureIdBits.clear();
2529 } else {
2530 BitSet32 upGestureIdBits;
2531 if (finishPreviousGesture) {
2532 upGestureIdBits = dispatchedGestureIdBits;
2533 } else {
2534 upGestureIdBits.value =
2535 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2536 }
2537 while (!upGestureIdBits.isEmpty()) {
2538 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2539
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002540 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002541 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002542 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002543 mPointerGesture.lastGestureCoords,
2544 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2545 0, mPointerGesture.downTime);
2546
2547 dispatchedGestureIdBits.clearBit(id);
2548 }
2549 }
2550 }
2551
2552 // Send motion events for all pointers that moved.
2553 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002554 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002555 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002556 mPointerGesture.currentGestureProperties,
2557 mPointerGesture.currentGestureCoords,
2558 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2559 mPointerGesture.downTime);
2560 }
2561
2562 // Send motion events for all pointers that went down.
2563 if (down) {
2564 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2565 ~dispatchedGestureIdBits.value);
2566 while (!downGestureIdBits.isEmpty()) {
2567 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2568 dispatchedGestureIdBits.markBit(id);
2569
2570 if (dispatchedGestureIdBits.count() == 1) {
2571 mPointerGesture.downTime = when;
2572 }
2573
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002574 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002575 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002576 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002577 mPointerGesture.currentGestureCoords,
2578 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2579 0, mPointerGesture.downTime);
2580 }
2581 }
2582
2583 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002584 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002585 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2586 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002587 mPointerGesture.currentGestureProperties,
2588 mPointerGesture.currentGestureCoords,
2589 mPointerGesture.currentGestureIdToIndex,
2590 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2591 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2592 // Synthesize a hover move event after all pointers go up to indicate that
2593 // the pointer is hovering again even if the user is not currently touching
2594 // the touch pad. This ensures that a view will receive a fresh hover enter
2595 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002596 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002597
2598 PointerProperties pointerProperties;
2599 pointerProperties.clear();
2600 pointerProperties.id = 0;
2601 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2602
2603 PointerCoords pointerCoords;
2604 pointerCoords.clear();
2605 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2606 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2607
2608 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002609 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002610 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002611 metaState, buttonState, MotionClassification::NONE,
2612 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2613 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002614 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002615 }
2616
2617 // Update state.
2618 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2619 if (!down) {
2620 mPointerGesture.lastGestureIdBits.clear();
2621 } else {
2622 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2623 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2624 uint32_t id = idBits.clearFirstMarkedBit();
2625 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2626 mPointerGesture.lastGestureProperties[index].copyFrom(
2627 mPointerGesture.currentGestureProperties[index]);
2628 mPointerGesture.lastGestureCoords[index].copyFrom(
2629 mPointerGesture.currentGestureCoords[index]);
2630 mPointerGesture.lastGestureIdToIndex[id] = index;
2631 }
2632 }
2633}
2634
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002635void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002636 // Cancel previously dispatches pointers.
2637 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2638 int32_t metaState = getContext()->getGlobalMetaState();
2639 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002640 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2641 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002642 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2643 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2644 0, 0, mPointerGesture.downTime);
2645 }
2646
2647 // Reset the current pointer gesture.
2648 mPointerGesture.reset();
2649 mPointerVelocityControl.reset();
2650
2651 // Remove any current spots.
2652 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002653 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002654 mPointerController->clearSpots();
2655 }
2656}
2657
2658bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2659 bool* outFinishPreviousGesture, bool isTimeout) {
2660 *outCancelPreviousGesture = false;
2661 *outFinishPreviousGesture = false;
2662
2663 // Handle TAP timeout.
2664 if (isTimeout) {
2665#if DEBUG_GESTURES
2666 ALOGD("Gestures: Processing timeout");
2667#endif
2668
Michael Wright227c5542020-07-02 18:30:52 +01002669 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002670 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2671 // The tap/drag timeout has not yet expired.
2672 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2673 mConfig.pointerGestureTapDragInterval);
2674 } else {
2675 // The tap is finished.
2676#if DEBUG_GESTURES
2677 ALOGD("Gestures: TAP finished");
2678#endif
2679 *outFinishPreviousGesture = true;
2680
2681 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002682 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002683 mPointerGesture.currentGestureIdBits.clear();
2684
2685 mPointerVelocityControl.reset();
2686 return true;
2687 }
2688 }
2689
2690 // We did not handle this timeout.
2691 return false;
2692 }
2693
2694 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2695 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2696
2697 // Update the velocity tracker.
2698 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002699 std::vector<VelocityTracker::Position> positions;
2700 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002701 uint32_t id = idBits.clearFirstMarkedBit();
2702 const RawPointerData::Pointer& pointer =
2703 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002704 float x = pointer.x * mPointerXMovementScale;
2705 float y = pointer.y * mPointerYMovementScale;
2706 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002707 }
2708 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2709 positions);
2710 }
2711
2712 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2713 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002714 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2715 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2716 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002717 mPointerGesture.resetTap();
2718 }
2719
2720 // Pick a new active touch id if needed.
2721 // Choose an arbitrary pointer that just went down, if there is one.
2722 // Otherwise choose an arbitrary remaining pointer.
2723 // This guarantees we always have an active touch id when there is at least one pointer.
2724 // We keep the same active touch id for as long as possible.
2725 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2726 int32_t activeTouchId = lastActiveTouchId;
2727 if (activeTouchId < 0) {
2728 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2729 activeTouchId = mPointerGesture.activeTouchId =
2730 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2731 mPointerGesture.firstTouchTime = when;
2732 }
2733 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2734 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2735 activeTouchId = mPointerGesture.activeTouchId =
2736 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2737 } else {
2738 activeTouchId = mPointerGesture.activeTouchId = -1;
2739 }
2740 }
2741
2742 // Determine whether we are in quiet time.
2743 bool isQuietTime = false;
2744 if (activeTouchId < 0) {
2745 mPointerGesture.resetQuietTime();
2746 } else {
2747 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2748 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002749 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2750 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2751 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002752 currentFingerCount < 2) {
2753 // Enter quiet time when exiting swipe or freeform state.
2754 // This is to prevent accidentally entering the hover state and flinging the
2755 // pointer when finishing a swipe and there is still one pointer left onscreen.
2756 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002757 } else if (mPointerGesture.lastGestureMode ==
2758 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002759 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2760 // Enter quiet time when releasing the button and there are still two or more
2761 // fingers down. This may indicate that one finger was used to press the button
2762 // but it has not gone up yet.
2763 isQuietTime = true;
2764 }
2765 if (isQuietTime) {
2766 mPointerGesture.quietTime = when;
2767 }
2768 }
2769 }
2770
2771 // Switch states based on button and pointer state.
2772 if (isQuietTime) {
2773 // Case 1: Quiet time. (QUIET)
2774#if DEBUG_GESTURES
2775 ALOGD("Gestures: QUIET for next %0.3fms",
2776 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2777#endif
Michael Wright227c5542020-07-02 18:30:52 +01002778 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002779 *outFinishPreviousGesture = true;
2780 }
2781
2782 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002783 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002784 mPointerGesture.currentGestureIdBits.clear();
2785
2786 mPointerVelocityControl.reset();
2787 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2788 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2789 // The pointer follows the active touch point.
2790 // Emit DOWN, MOVE, UP events at the pointer location.
2791 //
2792 // Only the active touch matters; other fingers are ignored. This policy helps
2793 // to handle the case where the user places a second finger on the touch pad
2794 // to apply the necessary force to depress an integrated button below the surface.
2795 // We don't want the second finger to be delivered to applications.
2796 //
2797 // For this to work well, we need to make sure to track the pointer that is really
2798 // active. If the user first puts one finger down to click then adds another
2799 // finger to drag then the active pointer should switch to the finger that is
2800 // being dragged.
2801#if DEBUG_GESTURES
2802 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2803 "currentFingerCount=%d",
2804 activeTouchId, currentFingerCount);
2805#endif
2806 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002807 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002808 *outFinishPreviousGesture = true;
2809 mPointerGesture.activeGestureId = 0;
2810 }
2811
2812 // Switch pointers if needed.
2813 // Find the fastest pointer and follow it.
2814 if (activeTouchId >= 0 && currentFingerCount > 1) {
2815 int32_t bestId = -1;
2816 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2817 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2818 uint32_t id = idBits.clearFirstMarkedBit();
2819 float vx, vy;
2820 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2821 float speed = hypotf(vx, vy);
2822 if (speed > bestSpeed) {
2823 bestId = id;
2824 bestSpeed = speed;
2825 }
2826 }
2827 }
2828 if (bestId >= 0 && bestId != activeTouchId) {
2829 mPointerGesture.activeTouchId = activeTouchId = bestId;
2830#if DEBUG_GESTURES
2831 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2832 "bestId=%d, bestSpeed=%0.3f",
2833 bestId, bestSpeed);
2834#endif
2835 }
2836 }
2837
2838 float deltaX = 0, deltaY = 0;
2839 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2840 const RawPointerData::Pointer& currentPointer =
2841 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2842 const RawPointerData::Pointer& lastPointer =
2843 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2844 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2845 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2846
2847 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2848 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2849
2850 // Move the pointer using a relative motion.
2851 // When using spots, the click will occur at the position of the anchor
2852 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002853 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 } else {
2855 mPointerVelocityControl.reset();
2856 }
2857
Prabir Pradhand7482e72021-03-09 13:54:55 -08002858 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859
Michael Wright227c5542020-07-02 18:30:52 +01002860 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002861 mPointerGesture.currentGestureIdBits.clear();
2862 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2863 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2864 mPointerGesture.currentGestureProperties[0].clear();
2865 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2866 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2867 mPointerGesture.currentGestureCoords[0].clear();
2868 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2869 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2870 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2871 } else if (currentFingerCount == 0) {
2872 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002873 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002874 *outFinishPreviousGesture = true;
2875 }
2876
2877 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2878 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2879 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002880 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2881 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002882 lastFingerCount == 1) {
2883 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002884 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2886 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2887#if DEBUG_GESTURES
2888 ALOGD("Gestures: TAP");
2889#endif
2890
2891 mPointerGesture.tapUpTime = when;
2892 getContext()->requestTimeoutAtTime(when +
2893 mConfig.pointerGestureTapDragInterval);
2894
2895 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002896 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002897 mPointerGesture.currentGestureIdBits.clear();
2898 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2899 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2900 mPointerGesture.currentGestureProperties[0].clear();
2901 mPointerGesture.currentGestureProperties[0].id =
2902 mPointerGesture.activeGestureId;
2903 mPointerGesture.currentGestureProperties[0].toolType =
2904 AMOTION_EVENT_TOOL_TYPE_FINGER;
2905 mPointerGesture.currentGestureCoords[0].clear();
2906 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2907 mPointerGesture.tapX);
2908 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2909 mPointerGesture.tapY);
2910 mPointerGesture.currentGestureCoords[0]
2911 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2912
2913 tapped = true;
2914 } else {
2915#if DEBUG_GESTURES
2916 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2917 y - mPointerGesture.tapY);
2918#endif
2919 }
2920 } else {
2921#if DEBUG_GESTURES
2922 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2923 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2924 (when - mPointerGesture.tapDownTime) * 0.000001f);
2925 } else {
2926 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2927 }
2928#endif
2929 }
2930 }
2931
2932 mPointerVelocityControl.reset();
2933
2934 if (!tapped) {
2935#if DEBUG_GESTURES
2936 ALOGD("Gestures: NEUTRAL");
2937#endif
2938 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002939 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002940 mPointerGesture.currentGestureIdBits.clear();
2941 }
2942 } else if (currentFingerCount == 1) {
2943 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2944 // The pointer follows the active touch point.
2945 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2946 // When in TAP_DRAG, emit MOVE events at the pointer location.
2947 ALOG_ASSERT(activeTouchId >= 0);
2948
Michael Wright227c5542020-07-02 18:30:52 +01002949 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2950 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002952 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002953 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2954 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002955 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002956 } else {
2957#if DEBUG_GESTURES
2958 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2959 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2960#endif
2961 }
2962 } else {
2963#if DEBUG_GESTURES
2964 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2965 (when - mPointerGesture.tapUpTime) * 0.000001f);
2966#endif
2967 }
Michael Wright227c5542020-07-02 18:30:52 +01002968 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2969 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 }
2971
2972 float deltaX = 0, deltaY = 0;
2973 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2974 const RawPointerData::Pointer& currentPointer =
2975 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2976 const RawPointerData::Pointer& lastPointer =
2977 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2978 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2979 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2980
2981 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2982 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2983
2984 // Move the pointer using a relative motion.
2985 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002986 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002987 } else {
2988 mPointerVelocityControl.reset();
2989 }
2990
2991 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002992 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002993#if DEBUG_GESTURES
2994 ALOGD("Gestures: TAP_DRAG");
2995#endif
2996 down = true;
2997 } else {
2998#if DEBUG_GESTURES
2999 ALOGD("Gestures: HOVER");
3000#endif
Michael Wright227c5542020-07-02 18:30:52 +01003001 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003002 *outFinishPreviousGesture = true;
3003 }
3004 mPointerGesture.activeGestureId = 0;
3005 down = false;
3006 }
3007
Prabir Pradhand7482e72021-03-09 13:54:55 -08003008 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003009
3010 mPointerGesture.currentGestureIdBits.clear();
3011 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3012 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3013 mPointerGesture.currentGestureProperties[0].clear();
3014 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3015 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3016 mPointerGesture.currentGestureCoords[0].clear();
3017 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3018 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3019 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3020 down ? 1.0f : 0.0f);
3021
3022 if (lastFingerCount == 0 && currentFingerCount != 0) {
3023 mPointerGesture.resetTap();
3024 mPointerGesture.tapDownTime = when;
3025 mPointerGesture.tapX = x;
3026 mPointerGesture.tapY = y;
3027 }
3028 } else {
3029 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3030 // We need to provide feedback for each finger that goes down so we cannot wait
3031 // for the fingers to move before deciding what to do.
3032 //
3033 // The ambiguous case is deciding what to do when there are two fingers down but they
3034 // have not moved enough to determine whether they are part of a drag or part of a
3035 // freeform gesture, or just a press or long-press at the pointer location.
3036 //
3037 // When there are two fingers we start with the PRESS hypothesis and we generate a
3038 // down at the pointer location.
3039 //
3040 // When the two fingers move enough or when additional fingers are added, we make
3041 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3042 ALOG_ASSERT(activeTouchId >= 0);
3043
3044 bool settled = when >=
3045 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003046 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3047 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3048 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003049 *outFinishPreviousGesture = true;
3050 } else if (!settled && currentFingerCount > lastFingerCount) {
3051 // Additional pointers have gone down but not yet settled.
3052 // Reset the gesture.
3053#if DEBUG_GESTURES
3054 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3055 "settle time remaining %0.3fms",
3056 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3057 when) * 0.000001f);
3058#endif
3059 *outCancelPreviousGesture = true;
3060 } else {
3061 // Continue previous gesture.
3062 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3063 }
3064
3065 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003066 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003067 mPointerGesture.activeGestureId = 0;
3068 mPointerGesture.referenceIdBits.clear();
3069 mPointerVelocityControl.reset();
3070
3071 // Use the centroid and pointer location as the reference points for the gesture.
3072#if DEBUG_GESTURES
3073 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3074 "settle time remaining %0.3fms",
3075 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3076 when) * 0.000001f);
3077#endif
3078 mCurrentRawState.rawPointerData
3079 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3080 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003081 auto [x, y] = getMouseCursorPosition();
3082 mPointerGesture.referenceGestureX = x;
3083 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003084 }
3085
3086 // Clear the reference deltas for fingers not yet included in the reference calculation.
3087 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3088 ~mPointerGesture.referenceIdBits.value);
3089 !idBits.isEmpty();) {
3090 uint32_t id = idBits.clearFirstMarkedBit();
3091 mPointerGesture.referenceDeltas[id].dx = 0;
3092 mPointerGesture.referenceDeltas[id].dy = 0;
3093 }
3094 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3095
3096 // Add delta for all fingers and calculate a common movement delta.
3097 float commonDeltaX = 0, commonDeltaY = 0;
3098 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3099 mCurrentCookedState.fingerIdBits.value);
3100 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3101 bool first = (idBits == commonIdBits);
3102 uint32_t id = idBits.clearFirstMarkedBit();
3103 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3104 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3105 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3106 delta.dx += cpd.x - lpd.x;
3107 delta.dy += cpd.y - lpd.y;
3108
3109 if (first) {
3110 commonDeltaX = delta.dx;
3111 commonDeltaY = delta.dy;
3112 } else {
3113 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3114 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3115 }
3116 }
3117
3118 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003119 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003120 float dist[MAX_POINTER_ID + 1];
3121 int32_t distOverThreshold = 0;
3122 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3123 uint32_t id = idBits.clearFirstMarkedBit();
3124 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3125 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3126 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3127 distOverThreshold += 1;
3128 }
3129 }
3130
3131 // Only transition when at least two pointers have moved further than
3132 // the minimum distance threshold.
3133 if (distOverThreshold >= 2) {
3134 if (currentFingerCount > 2) {
3135 // There are more than two pointers, switch to FREEFORM.
3136#if DEBUG_GESTURES
3137 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3138 currentFingerCount);
3139#endif
3140 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003141 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003142 } else {
3143 // There are exactly two pointers.
3144 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3145 uint32_t id1 = idBits.clearFirstMarkedBit();
3146 uint32_t id2 = idBits.firstMarkedBit();
3147 const RawPointerData::Pointer& p1 =
3148 mCurrentRawState.rawPointerData.pointerForId(id1);
3149 const RawPointerData::Pointer& p2 =
3150 mCurrentRawState.rawPointerData.pointerForId(id2);
3151 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3152 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3153 // There are two pointers but they are too far apart for a SWIPE,
3154 // switch to FREEFORM.
3155#if DEBUG_GESTURES
3156 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3157 mutualDistance, mPointerGestureMaxSwipeWidth);
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 } else {
3162 // There are two pointers. Wait for both pointers to start moving
3163 // before deciding whether this is a SWIPE or FREEFORM gesture.
3164 float dist1 = dist[id1];
3165 float dist2 = dist[id2];
3166 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3167 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3168 // Calculate the dot product of the displacement vectors.
3169 // When the vectors are oriented in approximately the same direction,
3170 // the angle betweeen them is near zero and the cosine of the angle
3171 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3172 // mag(v2).
3173 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3174 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3175 float dx1 = delta1.dx * mPointerXZoomScale;
3176 float dy1 = delta1.dy * mPointerYZoomScale;
3177 float dx2 = delta2.dx * mPointerXZoomScale;
3178 float dy2 = delta2.dy * mPointerYZoomScale;
3179 float dot = dx1 * dx2 + dy1 * dy2;
3180 float cosine = dot / (dist1 * dist2); // denominator always > 0
3181 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3182 // Pointers are moving in the same direction. Switch to SWIPE.
3183#if DEBUG_GESTURES
3184 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3185 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3186 "cosine %0.3f >= %0.3f",
3187 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3188 mConfig.pointerGestureMultitouchMinDistance, cosine,
3189 mConfig.pointerGestureSwipeTransitionAngleCosine);
3190#endif
Michael Wright227c5542020-07-02 18:30:52 +01003191 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003192 } else {
3193 // Pointers are moving in different directions. Switch to FREEFORM.
3194#if DEBUG_GESTURES
3195 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3196 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3197 "cosine %0.3f < %0.3f",
3198 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3199 mConfig.pointerGestureMultitouchMinDistance, cosine,
3200 mConfig.pointerGestureSwipeTransitionAngleCosine);
3201#endif
3202 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003203 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003204 }
3205 }
3206 }
3207 }
3208 }
Michael Wright227c5542020-07-02 18:30:52 +01003209 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003210 // Switch from SWIPE to FREEFORM if additional pointers go down.
3211 // Cancel previous gesture.
3212 if (currentFingerCount > 2) {
3213#if DEBUG_GESTURES
3214 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3215 currentFingerCount);
3216#endif
3217 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003218 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003219 }
3220 }
3221
3222 // Move the reference points based on the overall group motion of the fingers
3223 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003224 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003225 (commonDeltaX || commonDeltaY)) {
3226 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3227 uint32_t id = idBits.clearFirstMarkedBit();
3228 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3229 delta.dx = 0;
3230 delta.dy = 0;
3231 }
3232
3233 mPointerGesture.referenceTouchX += commonDeltaX;
3234 mPointerGesture.referenceTouchY += commonDeltaY;
3235
3236 commonDeltaX *= mPointerXMovementScale;
3237 commonDeltaY *= mPointerYMovementScale;
3238
3239 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3240 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3241
3242 mPointerGesture.referenceGestureX += commonDeltaX;
3243 mPointerGesture.referenceGestureY += commonDeltaY;
3244 }
3245
3246 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003247 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3248 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003249 // PRESS or SWIPE mode.
3250#if DEBUG_GESTURES
3251 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3252 "activeGestureId=%d, currentTouchPointerCount=%d",
3253 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3254#endif
3255 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3256
3257 mPointerGesture.currentGestureIdBits.clear();
3258 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3259 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3260 mPointerGesture.currentGestureProperties[0].clear();
3261 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3262 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3263 mPointerGesture.currentGestureCoords[0].clear();
3264 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3265 mPointerGesture.referenceGestureX);
3266 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3267 mPointerGesture.referenceGestureY);
3268 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003269 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003270 // FREEFORM mode.
3271#if DEBUG_GESTURES
3272 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3273 "activeGestureId=%d, currentTouchPointerCount=%d",
3274 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3275#endif
3276 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3277
3278 mPointerGesture.currentGestureIdBits.clear();
3279
3280 BitSet32 mappedTouchIdBits;
3281 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003282 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003283 // Initially, assign the active gesture id to the active touch point
3284 // if there is one. No other touch id bits are mapped yet.
3285 if (!*outCancelPreviousGesture) {
3286 mappedTouchIdBits.markBit(activeTouchId);
3287 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3288 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3289 mPointerGesture.activeGestureId;
3290 } else {
3291 mPointerGesture.activeGestureId = -1;
3292 }
3293 } else {
3294 // Otherwise, assume we mapped all touches from the previous frame.
3295 // Reuse all mappings that are still applicable.
3296 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3297 mCurrentCookedState.fingerIdBits.value;
3298 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3299
3300 // Check whether we need to choose a new active gesture id because the
3301 // current went went up.
3302 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3303 ~mCurrentCookedState.fingerIdBits.value);
3304 !upTouchIdBits.isEmpty();) {
3305 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3306 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3307 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3308 mPointerGesture.activeGestureId = -1;
3309 break;
3310 }
3311 }
3312 }
3313
3314#if DEBUG_GESTURES
3315 ALOGD("Gestures: FREEFORM follow up "
3316 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3317 "activeGestureId=%d",
3318 mappedTouchIdBits.value, usedGestureIdBits.value,
3319 mPointerGesture.activeGestureId);
3320#endif
3321
3322 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3323 for (uint32_t i = 0; i < currentFingerCount; i++) {
3324 uint32_t touchId = idBits.clearFirstMarkedBit();
3325 uint32_t gestureId;
3326 if (!mappedTouchIdBits.hasBit(touchId)) {
3327 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3328 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3329#if DEBUG_GESTURES
3330 ALOGD("Gestures: FREEFORM "
3331 "new mapping for touch id %d -> gesture id %d",
3332 touchId, gestureId);
3333#endif
3334 } else {
3335 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3336#if DEBUG_GESTURES
3337 ALOGD("Gestures: FREEFORM "
3338 "existing mapping for touch id %d -> gesture id %d",
3339 touchId, gestureId);
3340#endif
3341 }
3342 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3343 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3344
3345 const RawPointerData::Pointer& pointer =
3346 mCurrentRawState.rawPointerData.pointerForId(touchId);
3347 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3348 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3349 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3350
3351 mPointerGesture.currentGestureProperties[i].clear();
3352 mPointerGesture.currentGestureProperties[i].id = gestureId;
3353 mPointerGesture.currentGestureProperties[i].toolType =
3354 AMOTION_EVENT_TOOL_TYPE_FINGER;
3355 mPointerGesture.currentGestureCoords[i].clear();
3356 mPointerGesture.currentGestureCoords[i]
3357 .setAxisValue(AMOTION_EVENT_AXIS_X,
3358 mPointerGesture.referenceGestureX + deltaX);
3359 mPointerGesture.currentGestureCoords[i]
3360 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3361 mPointerGesture.referenceGestureY + deltaY);
3362 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3363 1.0f);
3364 }
3365
3366 if (mPointerGesture.activeGestureId < 0) {
3367 mPointerGesture.activeGestureId =
3368 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3369#if DEBUG_GESTURES
3370 ALOGD("Gestures: FREEFORM new "
3371 "activeGestureId=%d",
3372 mPointerGesture.activeGestureId);
3373#endif
3374 }
3375 }
3376 }
3377
3378 mPointerController->setButtonState(mCurrentRawState.buttonState);
3379
3380#if DEBUG_GESTURES
3381 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3382 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3383 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3384 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3385 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3386 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3387 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3388 uint32_t id = idBits.clearFirstMarkedBit();
3389 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3390 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3391 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3392 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3393 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3394 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3395 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3396 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3397 }
3398 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3399 uint32_t id = idBits.clearFirstMarkedBit();
3400 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3401 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3402 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3403 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3404 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3405 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3406 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3407 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3408 }
3409#endif
3410 return true;
3411}
3412
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003413void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003414 mPointerSimple.currentCoords.clear();
3415 mPointerSimple.currentProperties.clear();
3416
3417 bool down, hovering;
3418 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3419 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3420 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003421 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3422 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003423
3424 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3425 down = !hovering;
3426
Prabir Pradhand7482e72021-03-09 13:54:55 -08003427 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003428 mPointerSimple.currentCoords.copyFrom(
3429 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3430 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3431 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3432 mPointerSimple.currentProperties.id = 0;
3433 mPointerSimple.currentProperties.toolType =
3434 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3435 } else {
3436 down = false;
3437 hovering = false;
3438 }
3439
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003440 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003441}
3442
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003443void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3444 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003445}
3446
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003447void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003448 mPointerSimple.currentCoords.clear();
3449 mPointerSimple.currentProperties.clear();
3450
3451 bool down, hovering;
3452 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3453 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3454 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3455 float deltaX = 0, deltaY = 0;
3456 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3457 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3458 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3459 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3460 mPointerXMovementScale;
3461 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3462 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3463 mPointerYMovementScale;
3464
3465 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3466 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3467
Prabir Pradhand7482e72021-03-09 13:54:55 -08003468 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469 } else {
3470 mPointerVelocityControl.reset();
3471 }
3472
3473 down = isPointerDown(mCurrentRawState.buttonState);
3474 hovering = !down;
3475
Prabir Pradhand7482e72021-03-09 13:54:55 -08003476 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003477 mPointerSimple.currentCoords.copyFrom(
3478 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3479 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3480 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3481 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3482 hovering ? 0.0f : 1.0f);
3483 mPointerSimple.currentProperties.id = 0;
3484 mPointerSimple.currentProperties.toolType =
3485 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3486 } else {
3487 mPointerVelocityControl.reset();
3488
3489 down = false;
3490 hovering = false;
3491 }
3492
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003493 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003494}
3495
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003496void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3497 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003498
3499 mPointerVelocityControl.reset();
3500}
3501
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003502void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3503 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003504 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003505
3506 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003507 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003508 mPointerController->clearSpots();
3509 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003510 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003511 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003512 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003513 }
Garfield Tan9514d782020-11-10 16:37:23 -08003514 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515
Prabir Pradhand7482e72021-03-09 13:54:55 -08003516 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517
3518 if (mPointerSimple.down && !down) {
3519 mPointerSimple.down = false;
3520
3521 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003522 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3523 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003524 mLastRawState.buttonState, MotionClassification::NONE,
3525 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3526 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3527 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3528 /* videoFrames */ {});
3529 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003530 }
3531
3532 if (mPointerSimple.hovering && !hovering) {
3533 mPointerSimple.hovering = false;
3534
3535 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003536 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3537 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3538 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003539 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3540 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3541 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3542 /* videoFrames */ {});
3543 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003544 }
3545
3546 if (down) {
3547 if (!mPointerSimple.down) {
3548 mPointerSimple.down = true;
3549 mPointerSimple.downTime = when;
3550
3551 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003552 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003553 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3554 metaState, mCurrentRawState.buttonState,
3555 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3556 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3557 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3558 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3559 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003560 }
3561
3562 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003563 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3564 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003565 mCurrentRawState.buttonState, MotionClassification::NONE,
3566 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3567 &mPointerSimple.currentCoords, mOrientedXPrecision,
3568 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3569 mPointerSimple.downTime, /* videoFrames */ {});
3570 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571 }
3572
3573 if (hovering) {
3574 if (!mPointerSimple.hovering) {
3575 mPointerSimple.hovering = true;
3576
3577 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003578 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003579 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3580 metaState, mCurrentRawState.buttonState,
3581 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3582 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3583 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3584 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3585 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003586 }
3587
3588 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003589 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3590 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3591 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003592 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3593 &mPointerSimple.currentCoords, mOrientedXPrecision,
3594 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3595 mPointerSimple.downTime, /* videoFrames */ {});
3596 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003597 }
3598
3599 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3600 float vscroll = mCurrentRawState.rawVScroll;
3601 float hscroll = mCurrentRawState.rawHScroll;
3602 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3603 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3604
3605 // Send scroll.
3606 PointerCoords pointerCoords;
3607 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3608 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3609 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3610
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003611 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3612 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003613 mCurrentRawState.buttonState, MotionClassification::NONE,
3614 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3615 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3616 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3617 /* videoFrames */ {});
3618 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003619 }
3620
3621 // Save state.
3622 if (down || hovering) {
3623 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3624 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3625 } else {
3626 mPointerSimple.reset();
3627 }
3628}
3629
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003630void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003631 mPointerSimple.currentCoords.clear();
3632 mPointerSimple.currentProperties.clear();
3633
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003634 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003635}
3636
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003637void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3638 uint32_t source, int32_t action, int32_t actionButton,
3639 int32_t flags, int32_t metaState, int32_t buttonState,
3640 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003641 const PointerCoords* coords, const uint32_t* idToIndex,
3642 BitSet32 idBits, int32_t changedId, float xPrecision,
3643 float yPrecision, nsecs_t downTime) {
3644 PointerCoords pointerCoords[MAX_POINTERS];
3645 PointerProperties pointerProperties[MAX_POINTERS];
3646 uint32_t pointerCount = 0;
3647 while (!idBits.isEmpty()) {
3648 uint32_t id = idBits.clearFirstMarkedBit();
3649 uint32_t index = idToIndex[id];
3650 pointerProperties[pointerCount].copyFrom(properties[index]);
3651 pointerCoords[pointerCount].copyFrom(coords[index]);
3652
3653 if (changedId >= 0 && id == uint32_t(changedId)) {
3654 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3655 }
3656
3657 pointerCount += 1;
3658 }
3659
3660 ALOG_ASSERT(pointerCount != 0);
3661
3662 if (changedId >= 0 && pointerCount == 1) {
3663 // Replace initial down and final up action.
3664 // We can compare the action without masking off the changed pointer index
3665 // because we know the index is 0.
3666 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3667 action = AMOTION_EVENT_ACTION_DOWN;
3668 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003669 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3670 action = AMOTION_EVENT_ACTION_CANCEL;
3671 } else {
3672 action = AMOTION_EVENT_ACTION_UP;
3673 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003674 } else {
3675 // Can't happen.
3676 ALOG_ASSERT(false);
3677 }
3678 }
3679 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3680 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003681 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003682 auto [x, y] = getMouseCursorPosition();
3683 xCursorPosition = x;
3684 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003685 }
3686 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3687 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003688 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003689 std::for_each(frames.begin(), frames.end(),
3690 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003691 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3692 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003693 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3694 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3695 downTime, std::move(frames));
3696 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003697}
3698
3699bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3700 const PointerCoords* inCoords,
3701 const uint32_t* inIdToIndex,
3702 PointerProperties* outProperties,
3703 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3704 BitSet32 idBits) const {
3705 bool changed = false;
3706 while (!idBits.isEmpty()) {
3707 uint32_t id = idBits.clearFirstMarkedBit();
3708 uint32_t inIndex = inIdToIndex[id];
3709 uint32_t outIndex = outIdToIndex[id];
3710
3711 const PointerProperties& curInProperties = inProperties[inIndex];
3712 const PointerCoords& curInCoords = inCoords[inIndex];
3713 PointerProperties& curOutProperties = outProperties[outIndex];
3714 PointerCoords& curOutCoords = outCoords[outIndex];
3715
3716 if (curInProperties != curOutProperties) {
3717 curOutProperties.copyFrom(curInProperties);
3718 changed = true;
3719 }
3720
3721 if (curInCoords != curOutCoords) {
3722 curOutCoords.copyFrom(curInCoords);
3723 changed = true;
3724 }
3725 }
3726 return changed;
3727}
3728
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003729void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3730 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3731 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003732}
3733
Arthur Hung4197f6b2020-03-16 15:39:59 +08003734// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003735void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003736 // Scale to surface coordinate.
3737 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3738 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3739
arthurhunga36b28e2020-12-29 20:28:15 +08003740 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3741 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3742
Arthur Hung4197f6b2020-03-16 15:39:59 +08003743 // Rotate to surface coordinate.
3744 // 0 - no swap and reverse.
3745 // 90 - swap x/y and reverse y.
3746 // 180 - reverse x, y.
3747 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003748 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003749 case DISPLAY_ORIENTATION_0:
3750 x = xScaled + mXTranslate;
3751 y = yScaled + mYTranslate;
3752 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003753 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003754 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003755 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003756 break;
3757 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003758 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3759 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003760 break;
3761 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003762 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003763 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003764 break;
3765 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003766 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003767 }
3768}
3769
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003770bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003771 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3772 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3773
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003774 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003775 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003776 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003777 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003778}
3779
3780const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3781 for (const VirtualKey& virtualKey : mVirtualKeys) {
3782#if DEBUG_VIRTUAL_KEYS
3783 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3784 "left=%d, top=%d, right=%d, bottom=%d",
3785 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3786 virtualKey.hitRight, virtualKey.hitBottom);
3787#endif
3788
3789 if (virtualKey.isHit(x, y)) {
3790 return &virtualKey;
3791 }
3792 }
3793
3794 return nullptr;
3795}
3796
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003797void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3798 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3799 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003800
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003801 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003802
3803 if (currentPointerCount == 0) {
3804 // No pointers to assign.
3805 return;
3806 }
3807
3808 if (lastPointerCount == 0) {
3809 // All pointers are new.
3810 for (uint32_t i = 0; i < currentPointerCount; i++) {
3811 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003812 current.rawPointerData.pointers[i].id = id;
3813 current.rawPointerData.idToIndex[id] = i;
3814 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003815 }
3816 return;
3817 }
3818
3819 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003820 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003821 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003822 uint32_t id = last.rawPointerData.pointers[0].id;
3823 current.rawPointerData.pointers[0].id = id;
3824 current.rawPointerData.idToIndex[id] = 0;
3825 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003826 return;
3827 }
3828
3829 // General case.
3830 // We build a heap of squared euclidean distances between current and last pointers
3831 // associated with the current and last pointer indices. Then, we find the best
3832 // match (by distance) for each current pointer.
3833 // The pointers must have the same tool type but it is possible for them to
3834 // transition from hovering to touching or vice-versa while retaining the same id.
3835 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3836
3837 uint32_t heapSize = 0;
3838 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3839 currentPointerIndex++) {
3840 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3841 lastPointerIndex++) {
3842 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003843 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003844 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003845 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003846 if (currentPointer.toolType == lastPointer.toolType) {
3847 int64_t deltaX = currentPointer.x - lastPointer.x;
3848 int64_t deltaY = currentPointer.y - lastPointer.y;
3849
3850 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3851
3852 // Insert new element into the heap (sift up).
3853 heap[heapSize].currentPointerIndex = currentPointerIndex;
3854 heap[heapSize].lastPointerIndex = lastPointerIndex;
3855 heap[heapSize].distance = distance;
3856 heapSize += 1;
3857 }
3858 }
3859 }
3860
3861 // Heapify
3862 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3863 startIndex -= 1;
3864 for (uint32_t parentIndex = startIndex;;) {
3865 uint32_t childIndex = parentIndex * 2 + 1;
3866 if (childIndex >= heapSize) {
3867 break;
3868 }
3869
3870 if (childIndex + 1 < heapSize &&
3871 heap[childIndex + 1].distance < heap[childIndex].distance) {
3872 childIndex += 1;
3873 }
3874
3875 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3876 break;
3877 }
3878
3879 swap(heap[parentIndex], heap[childIndex]);
3880 parentIndex = childIndex;
3881 }
3882 }
3883
3884#if DEBUG_POINTER_ASSIGNMENT
3885 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3886 for (size_t i = 0; i < heapSize; i++) {
3887 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3888 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3889 }
3890#endif
3891
3892 // Pull matches out by increasing order of distance.
3893 // To avoid reassigning pointers that have already been matched, the loop keeps track
3894 // of which last and current pointers have been matched using the matchedXXXBits variables.
3895 // It also tracks the used pointer id bits.
3896 BitSet32 matchedLastBits(0);
3897 BitSet32 matchedCurrentBits(0);
3898 BitSet32 usedIdBits(0);
3899 bool first = true;
3900 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3901 while (heapSize > 0) {
3902 if (first) {
3903 // The first time through the loop, we just consume the root element of
3904 // the heap (the one with smallest distance).
3905 first = false;
3906 } else {
3907 // Previous iterations consumed the root element of the heap.
3908 // Pop root element off of the heap (sift down).
3909 heap[0] = heap[heapSize];
3910 for (uint32_t parentIndex = 0;;) {
3911 uint32_t childIndex = parentIndex * 2 + 1;
3912 if (childIndex >= heapSize) {
3913 break;
3914 }
3915
3916 if (childIndex + 1 < heapSize &&
3917 heap[childIndex + 1].distance < heap[childIndex].distance) {
3918 childIndex += 1;
3919 }
3920
3921 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3922 break;
3923 }
3924
3925 swap(heap[parentIndex], heap[childIndex]);
3926 parentIndex = childIndex;
3927 }
3928
3929#if DEBUG_POINTER_ASSIGNMENT
3930 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003931 for (size_t j = 0; j < heapSize; j++) {
3932 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3933 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003934 }
3935#endif
3936 }
3937
3938 heapSize -= 1;
3939
3940 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3941 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3942
3943 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3944 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3945
3946 matchedCurrentBits.markBit(currentPointerIndex);
3947 matchedLastBits.markBit(lastPointerIndex);
3948
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003949 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3950 current.rawPointerData.pointers[currentPointerIndex].id = id;
3951 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3952 current.rawPointerData.markIdBit(id,
3953 current.rawPointerData.isHovering(
3954 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003955 usedIdBits.markBit(id);
3956
3957#if DEBUG_POINTER_ASSIGNMENT
3958 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3959 ", distance=%" PRIu64,
3960 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3961#endif
3962 break;
3963 }
3964 }
3965
3966 // Assign fresh ids to pointers that were not matched in the process.
3967 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3968 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3969 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3970
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003971 current.rawPointerData.pointers[currentPointerIndex].id = id;
3972 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3973 current.rawPointerData.markIdBit(id,
3974 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003975
3976#if DEBUG_POINTER_ASSIGNMENT
3977 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3978#endif
3979 }
3980}
3981
3982int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3983 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3984 return AKEY_STATE_VIRTUAL;
3985 }
3986
3987 for (const VirtualKey& virtualKey : mVirtualKeys) {
3988 if (virtualKey.keyCode == keyCode) {
3989 return AKEY_STATE_UP;
3990 }
3991 }
3992
3993 return AKEY_STATE_UNKNOWN;
3994}
3995
3996int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3997 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3998 return AKEY_STATE_VIRTUAL;
3999 }
4000
4001 for (const VirtualKey& virtualKey : mVirtualKeys) {
4002 if (virtualKey.scanCode == scanCode) {
4003 return AKEY_STATE_UP;
4004 }
4005 }
4006
4007 return AKEY_STATE_UNKNOWN;
4008}
4009
4010bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4011 const int32_t* keyCodes, uint8_t* outFlags) {
4012 for (const VirtualKey& virtualKey : mVirtualKeys) {
4013 for (size_t i = 0; i < numCodes; i++) {
4014 if (virtualKey.keyCode == keyCodes[i]) {
4015 outFlags[i] = 1;
4016 }
4017 }
4018 }
4019
4020 return true;
4021}
4022
4023std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4024 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004025 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004026 return std::make_optional(mPointerController->getDisplayId());
4027 } else {
4028 return std::make_optional(mViewport.displayId);
4029 }
4030 }
4031 return std::nullopt;
4032}
4033
Prabir Pradhand7482e72021-03-09 13:54:55 -08004034void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
4035 if (isPerWindowInputRotationEnabled()) {
4036 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4037 // space that is oriented with the viewport.
4038 rotateDelta(mViewport.orientation, &dx, &dy);
4039 }
4040
4041 mPointerController->move(dx, dy);
4042}
4043
4044std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4045 float x = 0;
4046 float y = 0;
4047 mPointerController->getPosition(&x, &y);
4048
4049 if (!isPerWindowInputRotationEnabled()) return {x, y};
4050 if (!mViewport.isValid()) return {x, y};
4051
4052 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4053 // to InputReader's un-rotated coordinate space.
4054 const int32_t orientation = getInverseRotation(mViewport.orientation);
4055 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4056 return {x, y};
4057}
4058
4059void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4060 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4061 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4062 // coordinate space that is oriented with the viewport.
4063 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4064 }
4065
4066 mPointerController->setPosition(x, y);
4067}
4068
4069void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4070 BitSet32 spotIdBits, int32_t displayId) {
4071 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4072
4073 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4074 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4075 float x = spotCoords[index].getX();
4076 float y = spotCoords[index].getY();
4077 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4078
4079 if (isPerWindowInputRotationEnabled()) {
4080 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4081 // coordinate space.
4082 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4083 }
4084
4085 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4086 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4087 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4088 }
4089
4090 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4091}
4092
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004093} // namespace android