blob: 17bbff8817ab317b570fc838060903b4ed295e32 [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 Pradhan3b134cc2021-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 Pradhan3b134cc2021-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 Pradhanac483a62021-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 Pradhan3b134cc2021-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 Pradhan3b134cc2021-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 Pradhanac483a62021-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 Pradhanac483a62021-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 {
lilinnandef700b2022-06-17 19:32:01 +0800816 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
817 !mConfig.showTouches) {
818 mPointerController->clearSpots();
819 }
Michael Wright17db18e2020-06-26 20:51:44 +0100820 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700821 }
822
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700823 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700824 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
825 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800826 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700827 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
828
829 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800830 mXScale = float(mRawSurfaceWidth) / rawWidth;
831 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700832 mXTranslate = -mSurfaceLeft;
833 mYTranslate = -mSurfaceTop;
834 mXPrecision = 1.0f / mXScale;
835 mYPrecision = 1.0f / mYScale;
836
837 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
838 mOrientedRanges.x.source = mSource;
839 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
840 mOrientedRanges.y.source = mSource;
841
842 configureVirtualKeys();
843
844 // Scale factor for terms that are not oriented in a particular axis.
845 // If the pixels are square then xScale == yScale otherwise we fake it
846 // by choosing an average.
847 mGeometricScale = avg(mXScale, mYScale);
848
849 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800850 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700851
852 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100853 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700854 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
855 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
856 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
857 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
858 } else {
859 mSizeScale = 0.0f;
860 }
861
862 mOrientedRanges.haveTouchSize = true;
863 mOrientedRanges.haveToolSize = true;
864 mOrientedRanges.haveSize = true;
865
866 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
867 mOrientedRanges.touchMajor.source = mSource;
868 mOrientedRanges.touchMajor.min = 0;
869 mOrientedRanges.touchMajor.max = diagonalSize;
870 mOrientedRanges.touchMajor.flat = 0;
871 mOrientedRanges.touchMajor.fuzz = 0;
872 mOrientedRanges.touchMajor.resolution = 0;
873
874 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
875 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
876
877 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
878 mOrientedRanges.toolMajor.source = mSource;
879 mOrientedRanges.toolMajor.min = 0;
880 mOrientedRanges.toolMajor.max = diagonalSize;
881 mOrientedRanges.toolMajor.flat = 0;
882 mOrientedRanges.toolMajor.fuzz = 0;
883 mOrientedRanges.toolMajor.resolution = 0;
884
885 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
886 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
887
888 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
889 mOrientedRanges.size.source = mSource;
890 mOrientedRanges.size.min = 0;
891 mOrientedRanges.size.max = 1.0;
892 mOrientedRanges.size.flat = 0;
893 mOrientedRanges.size.fuzz = 0;
894 mOrientedRanges.size.resolution = 0;
895 } else {
896 mSizeScale = 0.0f;
897 }
898
899 // Pressure factors.
900 mPressureScale = 0;
901 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100902 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
903 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 if (mCalibration.havePressureScale) {
905 mPressureScale = mCalibration.pressureScale;
906 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
907 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
908 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
909 }
910 }
911
912 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
913 mOrientedRanges.pressure.source = mSource;
914 mOrientedRanges.pressure.min = 0;
915 mOrientedRanges.pressure.max = pressureMax;
916 mOrientedRanges.pressure.flat = 0;
917 mOrientedRanges.pressure.fuzz = 0;
918 mOrientedRanges.pressure.resolution = 0;
919
920 // Tilt
921 mTiltXCenter = 0;
922 mTiltXScale = 0;
923 mTiltYCenter = 0;
924 mTiltYScale = 0;
925 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
926 if (mHaveTilt) {
927 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
928 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
929 mTiltXScale = M_PI / 180;
930 mTiltYScale = M_PI / 180;
931
Tatsunosuke Tobita35e05532021-06-30 14:49:32 +0900932 if (mRawPointerAxes.tiltX.resolution) {
933 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
934 }
935 if (mRawPointerAxes.tiltY.resolution) {
936 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
937 }
938
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700939 mOrientedRanges.haveTilt = true;
940
941 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
942 mOrientedRanges.tilt.source = mSource;
943 mOrientedRanges.tilt.min = 0;
944 mOrientedRanges.tilt.max = M_PI_2;
945 mOrientedRanges.tilt.flat = 0;
946 mOrientedRanges.tilt.fuzz = 0;
947 mOrientedRanges.tilt.resolution = 0;
948 }
949
950 // Orientation
951 mOrientationScale = 0;
952 if (mHaveTilt) {
953 mOrientedRanges.haveOrientation = true;
954
955 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
956 mOrientedRanges.orientation.source = mSource;
957 mOrientedRanges.orientation.min = -M_PI;
958 mOrientedRanges.orientation.max = M_PI;
959 mOrientedRanges.orientation.flat = 0;
960 mOrientedRanges.orientation.fuzz = 0;
961 mOrientedRanges.orientation.resolution = 0;
962 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100963 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700964 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100965 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966 if (mRawPointerAxes.orientation.valid) {
967 if (mRawPointerAxes.orientation.maxValue > 0) {
968 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
969 } else if (mRawPointerAxes.orientation.minValue < 0) {
970 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
971 } else {
972 mOrientationScale = 0;
973 }
974 }
975 }
976
977 mOrientedRanges.haveOrientation = true;
978
979 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
980 mOrientedRanges.orientation.source = mSource;
981 mOrientedRanges.orientation.min = -M_PI_2;
982 mOrientedRanges.orientation.max = M_PI_2;
983 mOrientedRanges.orientation.flat = 0;
984 mOrientedRanges.orientation.fuzz = 0;
985 mOrientedRanges.orientation.resolution = 0;
986 }
987
988 // Distance
989 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100990 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
991 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700992 if (mCalibration.haveDistanceScale) {
993 mDistanceScale = mCalibration.distanceScale;
994 } else {
995 mDistanceScale = 1.0f;
996 }
997 }
998
999 mOrientedRanges.haveDistance = true;
1000
1001 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
1002 mOrientedRanges.distance.source = mSource;
1003 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
1004 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
1005 mOrientedRanges.distance.flat = 0;
1006 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
1007 mOrientedRanges.distance.resolution = 0;
1008 }
1009
1010 // Compute oriented precision, scales and ranges.
1011 // Note that the maximum value reported is an inclusive maximum value so it is one
1012 // unit less than the total width or height of surface.
1013 switch (mSurfaceOrientation) {
1014 case DISPLAY_ORIENTATION_90:
1015 case DISPLAY_ORIENTATION_270:
1016 mOrientedXPrecision = mYPrecision;
1017 mOrientedYPrecision = mXPrecision;
1018
1019 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001020 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001021 mOrientedRanges.x.flat = 0;
1022 mOrientedRanges.x.fuzz = 0;
1023 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
1024
1025 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001026 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001027 mOrientedRanges.y.flat = 0;
1028 mOrientedRanges.y.fuzz = 0;
1029 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
1030 break;
1031
1032 default:
1033 mOrientedXPrecision = mXPrecision;
1034 mOrientedYPrecision = mYPrecision;
1035
1036 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001037 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001038 mOrientedRanges.x.flat = 0;
1039 mOrientedRanges.x.fuzz = 0;
1040 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1041
1042 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001043 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001044 mOrientedRanges.y.flat = 0;
1045 mOrientedRanges.y.fuzz = 0;
1046 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1047 break;
1048 }
1049
1050 // Location
1051 updateAffineTransformation();
1052
Michael Wright227c5542020-07-02 18:30:52 +01001053 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001054 // Compute pointer gesture detection parameters.
1055 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001056 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057
1058 // Scale movements such that one whole swipe of the touch pad covers a
1059 // given area relative to the diagonal size of the display when no acceleration
1060 // is applied.
1061 // Assume that the touch pad has a square aspect ratio such that movements in
1062 // X and Y of the same number of raw units cover the same physical distance.
1063 mPointerXMovementScale =
1064 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1065 mPointerYMovementScale = mPointerXMovementScale;
1066
1067 // Scale zooms to cover a smaller range of the display than movements do.
1068 // This value determines the area around the pointer that is affected by freeform
1069 // pointer gestures.
1070 mPointerXZoomScale =
1071 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1072 mPointerYZoomScale = mPointerXZoomScale;
1073
1074 // Max width between pointers to detect a swipe gesture is more than some fraction
1075 // of the diagonal axis of the touch pad. Touches that are wider than this are
1076 // translated into freeform gestures.
1077 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1078
1079 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001080 const nsecs_t readTime = when; // synthetic event
1081 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082 }
1083
1084 // Inform the dispatcher about the changes.
1085 *outResetNeeded = true;
1086 bumpGeneration();
1087 }
1088}
1089
1090void TouchInputMapper::dumpSurface(std::string& dump) {
1091 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001092 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1093 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001094 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1095 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001096 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1097 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001098 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1099 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1100 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1101 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1102 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1103}
1104
1105void TouchInputMapper::configureVirtualKeys() {
1106 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001107 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001108
1109 mVirtualKeys.clear();
1110
1111 if (virtualKeyDefinitions.size() == 0) {
1112 return;
1113 }
1114
1115 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1116 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1117 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1118 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1119
1120 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1121 VirtualKey virtualKey;
1122
1123 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1124 int32_t keyCode;
1125 int32_t dummyKeyMetaState;
1126 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001127 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1128 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001129 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1130 continue; // drop the key
1131 }
1132
1133 virtualKey.keyCode = keyCode;
1134 virtualKey.flags = flags;
1135
1136 // convert the key definition's display coordinates into touch coordinates for a hit box
1137 int32_t halfWidth = virtualKeyDefinition.width / 2;
1138 int32_t halfHeight = virtualKeyDefinition.height / 2;
1139
1140 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001141 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 touchScreenLeft;
1143 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001144 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001146 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1147 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001149 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1150 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 touchScreenTop;
1152 mVirtualKeys.push_back(virtualKey);
1153 }
1154}
1155
1156void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1157 if (!mVirtualKeys.empty()) {
1158 dump += INDENT3 "Virtual Keys:\n";
1159
1160 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1161 const VirtualKey& virtualKey = mVirtualKeys[i];
1162 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1163 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1164 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1165 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1166 }
1167 }
1168}
1169
1170void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001171 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 Calibration& out = mCalibration;
1173
1174 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 String8 sizeCalibrationString;
1177 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1178 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (sizeCalibrationString != "default") {
1189 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1190 }
1191 }
1192
1193 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1194 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1195 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1196
1197 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001198 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 String8 pressureCalibrationString;
1200 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1201 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 } else if (pressureCalibrationString != "default") {
1208 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1209 pressureCalibrationString.string());
1210 }
1211 }
1212
1213 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1214
1215 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 String8 orientationCalibrationString;
1218 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1219 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001220 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 } else if (orientationCalibrationString != "default") {
1226 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1227 orientationCalibrationString.string());
1228 }
1229 }
1230
1231 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001232 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 String8 distanceCalibrationString;
1234 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1235 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001236 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001238 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 } else if (distanceCalibrationString != "default") {
1240 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1241 distanceCalibrationString.string());
1242 }
1243 }
1244
1245 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1246
Michael Wright227c5542020-07-02 18:30:52 +01001247 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 String8 coverageCalibrationString;
1249 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1250 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001251 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001253 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 } else if (coverageCalibrationString != "default") {
1255 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1256 coverageCalibrationString.string());
1257 }
1258 }
1259}
1260
1261void TouchInputMapper::resolveCalibration() {
1262 // Size
1263 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001264 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1265 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001268 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270
1271 // Pressure
1272 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001273 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1274 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 }
1276 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001277 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 }
1279
1280 // Orientation
1281 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001282 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1283 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001286 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 }
1288
1289 // Distance
1290 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001291 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1292 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 }
1294 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001295 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 }
1297
1298 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001299 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1300 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 }
1302}
1303
1304void TouchInputMapper::dumpCalibration(std::string& dump) {
1305 dump += INDENT3 "Calibration:\n";
1306
1307 // Size
1308 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.size.calibration: none\n";
1311 break;
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.size.calibration: geometric\n";
1314 break;
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.size.calibration: diameter\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.size.calibration: box\n";
1320 break;
Michael Wright227c5542020-07-02 18:30:52 +01001321 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += INDENT4 "touch.size.calibration: area\n";
1323 break;
1324 default:
1325 ALOG_ASSERT(false);
1326 }
1327
1328 if (mCalibration.haveSizeScale) {
1329 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1330 }
1331
1332 if (mCalibration.haveSizeBias) {
1333 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1334 }
1335
1336 if (mCalibration.haveSizeIsSummed) {
1337 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1338 toString(mCalibration.sizeIsSummed));
1339 }
1340
1341 // Pressure
1342 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.pressure.calibration: none\n";
1345 break;
Michael Wright227c5542020-07-02 18:30:52 +01001346 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001347 dump += INDENT4 "touch.pressure.calibration: physical\n";
1348 break;
Michael Wright227c5542020-07-02 18:30:52 +01001349 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1351 break;
1352 default:
1353 ALOG_ASSERT(false);
1354 }
1355
1356 if (mCalibration.havePressureScale) {
1357 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1358 }
1359
1360 // Orientation
1361 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001362 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001363 dump += INDENT4 "touch.orientation.calibration: none\n";
1364 break;
Michael Wright227c5542020-07-02 18:30:52 +01001365 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1367 break;
Michael Wright227c5542020-07-02 18:30:52 +01001368 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001369 dump += INDENT4 "touch.orientation.calibration: vector\n";
1370 break;
1371 default:
1372 ALOG_ASSERT(false);
1373 }
1374
1375 // Distance
1376 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001377 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378 dump += INDENT4 "touch.distance.calibration: none\n";
1379 break;
Michael Wright227c5542020-07-02 18:30:52 +01001380 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001381 dump += INDENT4 "touch.distance.calibration: scaled\n";
1382 break;
1383 default:
1384 ALOG_ASSERT(false);
1385 }
1386
1387 if (mCalibration.haveDistanceScale) {
1388 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1389 }
1390
1391 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001392 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001393 dump += INDENT4 "touch.coverage.calibration: none\n";
1394 break;
Michael Wright227c5542020-07-02 18:30:52 +01001395 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001396 dump += INDENT4 "touch.coverage.calibration: box\n";
1397 break;
1398 default:
1399 ALOG_ASSERT(false);
1400 }
1401}
1402
1403void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1404 dump += INDENT3 "Affine Transformation:\n";
1405
1406 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1407 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1408 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1409 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1410 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1411 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1412}
1413
1414void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001415 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001416 mSurfaceOrientation);
1417}
1418
1419void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001420 mCursorButtonAccumulator.reset(getDeviceContext());
1421 mCursorScrollAccumulator.reset(getDeviceContext());
1422 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423
1424 mPointerVelocityControl.reset();
1425 mWheelXVelocityControl.reset();
1426 mWheelYVelocityControl.reset();
1427
1428 mRawStatesPending.clear();
1429 mCurrentRawState.clear();
1430 mCurrentCookedState.clear();
1431 mLastRawState.clear();
1432 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001433 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001434 mSentHoverEnter = false;
1435 mHavePointerIds = false;
1436 mCurrentMotionAborted = false;
1437 mDownTime = 0;
1438
1439 mCurrentVirtualKey.down = false;
1440
1441 mPointerGesture.reset();
1442 mPointerSimple.reset();
1443 resetExternalStylus();
1444
1445 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001446 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447 mPointerController->clearSpots();
1448 }
1449
1450 InputMapper::reset(when);
1451}
1452
1453void TouchInputMapper::resetExternalStylus() {
1454 mExternalStylusState.clear();
1455 mExternalStylusId = -1;
1456 mExternalStylusFusionTimeout = LLONG_MAX;
1457 mExternalStylusDataPending = false;
1458}
1459
1460void TouchInputMapper::clearStylusDataPendingFlags() {
1461 mExternalStylusDataPending = false;
1462 mExternalStylusFusionTimeout = LLONG_MAX;
1463}
1464
1465void TouchInputMapper::process(const RawEvent* rawEvent) {
1466 mCursorButtonAccumulator.process(rawEvent);
1467 mCursorScrollAccumulator.process(rawEvent);
1468 mTouchButtonAccumulator.process(rawEvent);
1469
1470 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001471 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001472 }
1473}
1474
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001475void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001476 // Push a new state.
1477 mRawStatesPending.emplace_back();
1478
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001479 RawState& next = mRawStatesPending.back();
1480 next.clear();
1481 next.when = when;
1482 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001483
1484 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001485 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001486 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1487
1488 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001489 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1490 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001491 mCursorScrollAccumulator.finishSync();
1492
1493 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001494 syncTouch(when, &next);
1495
1496 // The last RawState is the actually second to last, since we just added a new state
1497 const RawState& last =
1498 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001499
1500 // Assign pointer ids.
1501 if (!mHavePointerIds) {
1502 assignPointerIds(last, next);
1503 }
1504
1505#if DEBUG_RAW_EVENTS
1506 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001507 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001508 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1509 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1510 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1511 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001512#endif
1513
Arthur Hung9ad18942021-06-19 02:04:46 +00001514 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1515 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1516 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1517 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1518 next.rawPointerData.hoveringIdBits.value);
1519 }
1520
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521 processRawTouches(false /*timeout*/);
1522}
1523
1524void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001525 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001526 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001527 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001528 mCurrentCookedState.clear();
1529 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001530 return;
1531 }
1532
1533 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1534 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1535 // touching the current state will only observe the events that have been dispatched to the
1536 // rest of the pipeline.
1537 const size_t N = mRawStatesPending.size();
1538 size_t count;
1539 for (count = 0; count < N; count++) {
1540 const RawState& next = mRawStatesPending[count];
1541
1542 // A failure to assign the stylus id means that we're waiting on stylus data
1543 // and so should defer the rest of the pipeline.
1544 if (assignExternalStylusId(next, timeout)) {
1545 break;
1546 }
1547
1548 // All ready to go.
1549 clearStylusDataPendingFlags();
1550 mCurrentRawState.copyFrom(next);
1551 if (mCurrentRawState.when < mLastRawState.when) {
1552 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001553 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001554 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001555 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001556 }
1557 if (count != 0) {
1558 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1559 }
1560
1561 if (mExternalStylusDataPending) {
1562 if (timeout) {
1563 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1564 clearStylusDataPendingFlags();
1565 mCurrentRawState.copyFrom(mLastRawState);
1566#if DEBUG_STYLUS_FUSION
1567 ALOGD("Timeout expired, synthesizing event with new stylus data");
1568#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001569 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1570 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001571 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1572 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1573 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1574 }
1575 }
1576}
1577
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001578void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 // Always start with a clean state.
1580 mCurrentCookedState.clear();
1581
1582 // Apply stylus buttons to current raw state.
1583 applyExternalStylusButtonState(when);
1584
1585 // Handle policy on initial down or hover events.
1586 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1587 mCurrentRawState.rawPointerData.pointerCount != 0;
1588
1589 uint32_t policyFlags = 0;
1590 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1591 if (initialDown || buttonsPressed) {
1592 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001593 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001594 getContext()->fadePointer();
1595 }
1596
1597 if (mParameters.wake) {
1598 policyFlags |= POLICY_FLAG_WAKE;
1599 }
1600 }
1601
1602 // Consume raw off-screen touches before cooking pointer data.
1603 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001604 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001605 mCurrentRawState.rawPointerData.clear();
1606 }
1607
1608 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1609 // with cooked pointer data that has the same ids and indices as the raw data.
1610 // The following code can use either the raw or cooked data, as needed.
1611 cookPointerData();
1612
1613 // Apply stylus pressure to current cooked state.
1614 applyExternalStylusTouchState(when);
1615
1616 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001617 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1618 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001619 mCurrentCookedState.buttonState);
1620
1621 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001622 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001623 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1624 uint32_t id = idBits.clearFirstMarkedBit();
1625 const RawPointerData::Pointer& pointer =
1626 mCurrentRawState.rawPointerData.pointerForId(id);
1627 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1628 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1629 mCurrentCookedState.stylusIdBits.markBit(id);
1630 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1631 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1632 mCurrentCookedState.fingerIdBits.markBit(id);
1633 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1634 mCurrentCookedState.mouseIdBits.markBit(id);
1635 }
1636 }
1637 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1638 uint32_t id = idBits.clearFirstMarkedBit();
1639 const RawPointerData::Pointer& pointer =
1640 mCurrentRawState.rawPointerData.pointerForId(id);
1641 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1642 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1643 mCurrentCookedState.stylusIdBits.markBit(id);
1644 }
1645 }
1646
1647 // Stylus takes precedence over all tools, then mouse, then finger.
1648 PointerUsage pointerUsage = mPointerUsage;
1649 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1650 mCurrentCookedState.mouseIdBits.clear();
1651 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001652 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001653 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1654 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001655 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001656 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1657 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001658 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001659 }
1660
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001661 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001662 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001663 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001664
1665 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001666 dispatchButtonRelease(when, readTime, policyFlags);
1667 dispatchHoverExit(when, readTime, policyFlags);
1668 dispatchTouches(when, readTime, policyFlags);
1669 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1670 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001671 }
1672
1673 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1674 mCurrentMotionAborted = false;
1675 }
1676 }
1677
1678 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001679 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001680 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1681 mCurrentCookedState.buttonState);
1682
1683 // Clear some transient state.
1684 mCurrentRawState.rawVScroll = 0;
1685 mCurrentRawState.rawHScroll = 0;
1686
1687 // Copy current touch to last touch in preparation for the next cycle.
1688 mLastRawState.copyFrom(mCurrentRawState);
1689 mLastCookedState.copyFrom(mCurrentCookedState);
1690}
1691
Garfield Tanc734e4f2021-01-15 20:01:39 -08001692void TouchInputMapper::updateTouchSpots() {
1693 if (!mConfig.showTouches || mPointerController == nullptr) {
1694 return;
1695 }
1696
1697 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1698 // clear touch spots.
1699 if (mDeviceMode != DeviceMode::DIRECT &&
1700 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1701 return;
1702 }
1703
1704 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1705 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1706
1707 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001708 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1709 mCurrentCookedState.cookedPointerData.idToIndex,
1710 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001711}
1712
1713bool TouchInputMapper::isTouchScreen() {
1714 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1715 mParameters.hasAssociatedDisplay;
1716}
1717
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001718void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001719 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001720 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1721 }
1722}
1723
1724void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1725 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1726 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1727
1728 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1729 float pressure = mExternalStylusState.pressure;
1730 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1731 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1732 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1733 }
1734 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1735 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1736
1737 PointerProperties& properties =
1738 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1739 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1740 properties.toolType = mExternalStylusState.toolType;
1741 }
1742 }
1743}
1744
1745bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001746 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001747 return false;
1748 }
1749
1750 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1751 state.rawPointerData.pointerCount != 0;
1752 if (initialDown) {
1753 if (mExternalStylusState.pressure != 0.0f) {
1754#if DEBUG_STYLUS_FUSION
1755 ALOGD("Have both stylus and touch data, beginning fusion");
1756#endif
1757 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1758 } else if (timeout) {
1759#if DEBUG_STYLUS_FUSION
1760 ALOGD("Timeout expired, assuming touch is not a stylus.");
1761#endif
1762 resetExternalStylus();
1763 } else {
1764 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1765 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1766 }
1767#if DEBUG_STYLUS_FUSION
1768 ALOGD("No stylus data but stylus is connected, requesting timeout "
1769 "(%" PRId64 "ms)",
1770 mExternalStylusFusionTimeout);
1771#endif
1772 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1773 return true;
1774 }
1775 }
1776
1777 // Check if the stylus pointer has gone up.
1778 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1779#if DEBUG_STYLUS_FUSION
1780 ALOGD("Stylus pointer is going up");
1781#endif
1782 mExternalStylusId = -1;
1783 }
1784
1785 return false;
1786}
1787
1788void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001789 if (mDeviceMode == DeviceMode::POINTER) {
1790 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001791 // Since this is a synthetic event, we can consider its latency to be zero
1792 const nsecs_t readTime = when;
1793 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001794 }
Michael Wright227c5542020-07-02 18:30:52 +01001795 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001796 if (mExternalStylusFusionTimeout < when) {
1797 processRawTouches(true /*timeout*/);
1798 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1799 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1800 }
1801 }
1802}
1803
1804void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1805 mExternalStylusState.copyFrom(state);
1806 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1807 // We're either in the middle of a fused stream of data or we're waiting on data before
1808 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1809 // data.
1810 mExternalStylusDataPending = true;
1811 processRawTouches(false /*timeout*/);
1812 }
1813}
1814
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001815bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001816 // Check for release of a virtual key.
1817 if (mCurrentVirtualKey.down) {
1818 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1819 // Pointer went up while virtual key was down.
1820 mCurrentVirtualKey.down = false;
1821 if (!mCurrentVirtualKey.ignored) {
1822#if DEBUG_VIRTUAL_KEYS
1823 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1824 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1825#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001826 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001827 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1828 }
1829 return true;
1830 }
1831
1832 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1833 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1834 const RawPointerData::Pointer& pointer =
1835 mCurrentRawState.rawPointerData.pointerForId(id);
1836 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1837 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1838 // Pointer is still within the space of the virtual key.
1839 return true;
1840 }
1841 }
1842
1843 // Pointer left virtual key area or another pointer also went down.
1844 // Send key cancellation but do not consume the touch yet.
1845 // This is useful when the user swipes through from the virtual key area
1846 // into the main display surface.
1847 mCurrentVirtualKey.down = false;
1848 if (!mCurrentVirtualKey.ignored) {
1849#if DEBUG_VIRTUAL_KEYS
1850 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1851 mCurrentVirtualKey.scanCode);
1852#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001853 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1855 AKEY_EVENT_FLAG_CANCELED);
1856 }
1857 }
1858
1859 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1860 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1861 // Pointer just went down. Check for virtual key press or off-screen touches.
1862 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1863 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001864 // Exclude unscaled device for inside surface checking.
1865 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001866 // If exactly one pointer went down, check for virtual key hit.
1867 // Otherwise we will drop the entire stroke.
1868 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1869 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1870 if (virtualKey) {
1871 mCurrentVirtualKey.down = true;
1872 mCurrentVirtualKey.downTime = when;
1873 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1874 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1875 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001876 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1877 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001878
1879 if (!mCurrentVirtualKey.ignored) {
1880#if DEBUG_VIRTUAL_KEYS
1881 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1882 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1883#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001884 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001885 AKEY_EVENT_FLAG_FROM_SYSTEM |
1886 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1887 }
1888 }
1889 }
1890 return true;
1891 }
1892 }
1893
1894 // Disable all virtual key touches that happen within a short time interval of the
1895 // most recent touch within the screen area. The idea is to filter out stray
1896 // virtual key presses when interacting with the touch screen.
1897 //
1898 // Problems we're trying to solve:
1899 //
1900 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1901 // virtual key area that is implemented by a separate touch panel and accidentally
1902 // triggers a virtual key.
1903 //
1904 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1905 // area and accidentally triggers a virtual key. This often happens when virtual keys
1906 // are layed out below the screen near to where the on screen keyboard's space bar
1907 // is displayed.
1908 if (mConfig.virtualKeyQuietTime > 0 &&
1909 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001910 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001911 }
1912 return false;
1913}
1914
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001915void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001916 int32_t keyEventAction, int32_t keyEventFlags) {
1917 int32_t keyCode = mCurrentVirtualKey.keyCode;
1918 int32_t scanCode = mCurrentVirtualKey.scanCode;
1919 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001920 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921 policyFlags |= POLICY_FLAG_VIRTUAL;
1922
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001923 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1924 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1925 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001926 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001927}
1928
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001929void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001930 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1931 if (!currentIdBits.isEmpty()) {
1932 int32_t metaState = getContext()->getGlobalMetaState();
1933 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001934 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1935 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001936 mCurrentCookedState.cookedPointerData.pointerProperties,
1937 mCurrentCookedState.cookedPointerData.pointerCoords,
1938 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1939 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1940 mCurrentMotionAborted = true;
1941 }
1942}
1943
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001944void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001945 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1946 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1947 int32_t metaState = getContext()->getGlobalMetaState();
1948 int32_t buttonState = mCurrentCookedState.buttonState;
1949
1950 if (currentIdBits == lastIdBits) {
1951 if (!currentIdBits.isEmpty()) {
1952 // No pointer id changes so this is a move event.
1953 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001954 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1955 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001956 mCurrentCookedState.cookedPointerData.pointerProperties,
1957 mCurrentCookedState.cookedPointerData.pointerCoords,
1958 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1959 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1960 }
1961 } else {
1962 // There may be pointers going up and pointers going down and pointers moving
1963 // all at the same time.
1964 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1965 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1966 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1967 BitSet32 dispatchedIdBits(lastIdBits.value);
1968
1969 // Update last coordinates of pointers that have moved so that we observe the new
1970 // pointer positions at the same time as other pointers that have just gone up.
1971 bool moveNeeded =
1972 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1973 mCurrentCookedState.cookedPointerData.pointerCoords,
1974 mCurrentCookedState.cookedPointerData.idToIndex,
1975 mLastCookedState.cookedPointerData.pointerProperties,
1976 mLastCookedState.cookedPointerData.pointerCoords,
1977 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1978 if (buttonState != mLastCookedState.buttonState) {
1979 moveNeeded = true;
1980 }
1981
1982 // Dispatch pointer up events.
1983 while (!upIdBits.isEmpty()) {
1984 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001985 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001986 if (isCanceled) {
1987 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1988 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001989 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001990 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001991 mLastCookedState.cookedPointerData.pointerProperties,
1992 mLastCookedState.cookedPointerData.pointerCoords,
1993 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1994 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1995 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001996 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001997 }
1998
1999 // Dispatch move events if any of the remaining pointers moved from their old locations.
2000 // Although applications receive new locations as part of individual pointer up
2001 // events, they do not generally handle them except when presented in a move event.
2002 if (moveNeeded && !moveIdBits.isEmpty()) {
2003 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002004 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
2005 metaState, buttonState, 0,
2006 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002007 mCurrentCookedState.cookedPointerData.pointerCoords,
2008 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
2009 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2010 }
2011
2012 // Dispatch pointer down events using the new pointer locations.
2013 while (!downIdBits.isEmpty()) {
2014 uint32_t downId = downIdBits.clearFirstMarkedBit();
2015 dispatchedIdBits.markBit(downId);
2016
2017 if (dispatchedIdBits.count() == 1) {
2018 // First pointer is going down. Set down time.
2019 mDownTime = when;
2020 }
2021
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002022 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2023 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002024 mCurrentCookedState.cookedPointerData.pointerProperties,
2025 mCurrentCookedState.cookedPointerData.pointerCoords,
2026 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
2027 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2028 }
2029 }
2030}
2031
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002032void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002033 if (mSentHoverEnter &&
2034 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2035 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2036 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002037 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2038 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002039 mLastCookedState.cookedPointerData.pointerProperties,
2040 mLastCookedState.cookedPointerData.pointerCoords,
2041 mLastCookedState.cookedPointerData.idToIndex,
2042 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2043 mOrientedYPrecision, mDownTime);
2044 mSentHoverEnter = false;
2045 }
2046}
2047
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002048void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2049 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002050 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2051 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2052 int32_t metaState = getContext()->getGlobalMetaState();
2053 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002054 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2055 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002056 mCurrentCookedState.cookedPointerData.pointerProperties,
2057 mCurrentCookedState.cookedPointerData.pointerCoords,
2058 mCurrentCookedState.cookedPointerData.idToIndex,
2059 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2060 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2061 mSentHoverEnter = true;
2062 }
2063
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002064 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2065 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002066 mCurrentCookedState.cookedPointerData.pointerProperties,
2067 mCurrentCookedState.cookedPointerData.pointerCoords,
2068 mCurrentCookedState.cookedPointerData.idToIndex,
2069 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2070 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2071 }
2072}
2073
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002074void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002075 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2076 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2077 const int32_t metaState = getContext()->getGlobalMetaState();
2078 int32_t buttonState = mLastCookedState.buttonState;
2079 while (!releasedButtons.isEmpty()) {
2080 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2081 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002082 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002083 actionButton, 0, metaState, buttonState, 0,
2084 mCurrentCookedState.cookedPointerData.pointerProperties,
2085 mCurrentCookedState.cookedPointerData.pointerCoords,
2086 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2087 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2088 }
2089}
2090
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002091void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002092 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2093 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2094 const int32_t metaState = getContext()->getGlobalMetaState();
2095 int32_t buttonState = mLastCookedState.buttonState;
2096 while (!pressedButtons.isEmpty()) {
2097 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2098 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002099 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2100 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002101 mCurrentCookedState.cookedPointerData.pointerProperties,
2102 mCurrentCookedState.cookedPointerData.pointerCoords,
2103 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2104 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2105 }
2106}
2107
2108const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2109 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2110 return cookedPointerData.touchingIdBits;
2111 }
2112 return cookedPointerData.hoveringIdBits;
2113}
2114
2115void TouchInputMapper::cookPointerData() {
2116 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2117
2118 mCurrentCookedState.cookedPointerData.clear();
2119 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2120 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2121 mCurrentRawState.rawPointerData.hoveringIdBits;
2122 mCurrentCookedState.cookedPointerData.touchingIdBits =
2123 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002124 mCurrentCookedState.cookedPointerData.canceledIdBits =
2125 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002126
2127 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2128 mCurrentCookedState.buttonState = 0;
2129 } else {
2130 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2131 }
2132
2133 // Walk through the the active pointers and map device coordinates onto
2134 // surface coordinates and adjust for display orientation.
2135 for (uint32_t i = 0; i < currentPointerCount; i++) {
2136 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2137
2138 // Size
2139 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2140 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002141 case Calibration::SizeCalibration::GEOMETRIC:
2142 case Calibration::SizeCalibration::DIAMETER:
2143 case Calibration::SizeCalibration::BOX:
2144 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002145 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2146 touchMajor = in.touchMajor;
2147 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2148 toolMajor = in.toolMajor;
2149 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2150 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2151 : in.touchMajor;
2152 } else if (mRawPointerAxes.touchMajor.valid) {
2153 toolMajor = touchMajor = in.touchMajor;
2154 toolMinor = touchMinor =
2155 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2156 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2157 : in.touchMajor;
2158 } else if (mRawPointerAxes.toolMajor.valid) {
2159 touchMajor = toolMajor = in.toolMajor;
2160 touchMinor = toolMinor =
2161 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2162 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2163 : in.toolMajor;
2164 } else {
2165 ALOG_ASSERT(false,
2166 "No touch or tool axes. "
2167 "Size calibration should have been resolved to NONE.");
2168 touchMajor = 0;
2169 touchMinor = 0;
2170 toolMajor = 0;
2171 toolMinor = 0;
2172 size = 0;
2173 }
2174
2175 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2176 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2177 if (touchingCount > 1) {
2178 touchMajor /= touchingCount;
2179 touchMinor /= touchingCount;
2180 toolMajor /= touchingCount;
2181 toolMinor /= touchingCount;
2182 size /= touchingCount;
2183 }
2184 }
2185
Michael Wright227c5542020-07-02 18:30:52 +01002186 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002187 touchMajor *= mGeometricScale;
2188 touchMinor *= mGeometricScale;
2189 toolMajor *= mGeometricScale;
2190 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002191 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002192 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2193 touchMinor = touchMajor;
2194 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2195 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002196 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002197 touchMinor = touchMajor;
2198 toolMinor = toolMajor;
2199 }
2200
2201 mCalibration.applySizeScaleAndBias(&touchMajor);
2202 mCalibration.applySizeScaleAndBias(&touchMinor);
2203 mCalibration.applySizeScaleAndBias(&toolMajor);
2204 mCalibration.applySizeScaleAndBias(&toolMinor);
2205 size *= mSizeScale;
2206 break;
2207 default:
2208 touchMajor = 0;
2209 touchMinor = 0;
2210 toolMajor = 0;
2211 toolMinor = 0;
2212 size = 0;
2213 break;
2214 }
2215
2216 // Pressure
2217 float pressure;
2218 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002219 case Calibration::PressureCalibration::PHYSICAL:
2220 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002221 pressure = in.pressure * mPressureScale;
2222 break;
2223 default:
2224 pressure = in.isHovering ? 0 : 1;
2225 break;
2226 }
2227
2228 // Tilt and Orientation
2229 float tilt;
2230 float orientation;
2231 if (mHaveTilt) {
2232 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2233 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2234 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2235 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2236 } else {
2237 tilt = 0;
2238
2239 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002240 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002241 orientation = in.orientation * mOrientationScale;
2242 break;
Michael Wright227c5542020-07-02 18:30:52 +01002243 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2245 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2246 if (c1 != 0 || c2 != 0) {
2247 orientation = atan2f(c1, c2) * 0.5f;
2248 float confidence = hypotf(c1, c2);
2249 float scale = 1.0f + confidence / 16.0f;
2250 touchMajor *= scale;
2251 touchMinor /= scale;
2252 toolMajor *= scale;
2253 toolMinor /= scale;
2254 } else {
2255 orientation = 0;
2256 }
2257 break;
2258 }
2259 default:
2260 orientation = 0;
2261 }
2262 }
2263
2264 // Distance
2265 float distance;
2266 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002267 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002268 distance = in.distance * mDistanceScale;
2269 break;
2270 default:
2271 distance = 0;
2272 }
2273
2274 // Coverage
2275 int32_t rawLeft, rawTop, rawRight, rawBottom;
2276 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002277 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002278 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2279 rawRight = in.toolMinor & 0x0000ffff;
2280 rawBottom = in.toolMajor & 0x0000ffff;
2281 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2282 break;
2283 default:
2284 rawLeft = rawTop = rawRight = rawBottom = 0;
2285 break;
2286 }
2287
2288 // Adjust X,Y coords for device calibration
2289 // TODO: Adjust coverage coords?
2290 float xTransformed = in.x, yTransformed = in.y;
2291 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002292 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002293
2294 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002295 float left, top, right, bottom;
2296
2297 switch (mSurfaceOrientation) {
2298 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002299 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2300 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2301 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2302 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2303 orientation -= M_PI_2;
2304 if (mOrientedRanges.haveOrientation &&
2305 orientation < mOrientedRanges.orientation.min) {
2306 orientation +=
2307 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2308 }
2309 break;
2310 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002311 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2312 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2313 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2314 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2315 orientation -= M_PI;
2316 if (mOrientedRanges.haveOrientation &&
2317 orientation < mOrientedRanges.orientation.min) {
2318 orientation +=
2319 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2320 }
2321 break;
2322 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2324 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2325 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2326 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2327 orientation += M_PI_2;
2328 if (mOrientedRanges.haveOrientation &&
2329 orientation > mOrientedRanges.orientation.max) {
2330 orientation -=
2331 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2332 }
2333 break;
2334 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002335 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2336 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2337 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2338 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2339 break;
2340 }
2341
2342 // Write output coords.
2343 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2344 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002345 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2346 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2348 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2349 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2350 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2351 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2352 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2353 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002354 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2356 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2357 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2358 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2359 } else {
2360 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2361 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2362 }
2363
Chris Ye364fdb52020-08-05 15:07:56 -07002364 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002365 uint32_t id = in.id;
2366 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2367 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2368 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2369 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2370 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2371 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2372 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2373 }
2374
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 // Write output properties.
2376 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 properties.clear();
2378 properties.id = id;
2379 properties.toolType = in.toolType;
2380
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002381 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002383 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 }
2385}
2386
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002387void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 PointerUsage pointerUsage) {
2389 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002390 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 mPointerUsage = pointerUsage;
2392 }
2393
2394 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002395 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002396 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 break;
Michael Wright227c5542020-07-02 18:30:52 +01002398 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002399 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400 break;
Michael Wright227c5542020-07-02 18:30:52 +01002401 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002402 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 break;
Michael Wright227c5542020-07-02 18:30:52 +01002404 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 break;
2406 }
2407}
2408
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002409void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002411 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002412 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002413 break;
Michael Wright227c5542020-07-02 18:30:52 +01002414 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002415 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002416 break;
Michael Wright227c5542020-07-02 18:30:52 +01002417 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002418 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 break;
Michael Wright227c5542020-07-02 18:30:52 +01002420 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002421 break;
2422 }
2423
Michael Wright227c5542020-07-02 18:30:52 +01002424 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425}
2426
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002427void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2428 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429 // Update current gesture coordinates.
2430 bool cancelPreviousGesture, finishPreviousGesture;
2431 bool sendEvents =
2432 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2433 if (!sendEvents) {
2434 return;
2435 }
2436 if (finishPreviousGesture) {
2437 cancelPreviousGesture = false;
2438 }
2439
2440 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002441 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002442 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 if (finishPreviousGesture || cancelPreviousGesture) {
2444 mPointerController->clearSpots();
2445 }
2446
Michael Wright227c5542020-07-02 18:30:52 +01002447 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002448 setTouchSpots(mPointerGesture.currentGestureCoords,
2449 mPointerGesture.currentGestureIdToIndex,
2450 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451 }
2452 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002453 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454 }
2455
2456 // Show or hide the pointer if needed.
2457 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002458 case PointerGesture::Mode::NEUTRAL:
2459 case PointerGesture::Mode::QUIET:
2460 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2461 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002463 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 }
2465 break;
Michael Wright227c5542020-07-02 18:30:52 +01002466 case PointerGesture::Mode::TAP:
2467 case PointerGesture::Mode::TAP_DRAG:
2468 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2469 case PointerGesture::Mode::HOVER:
2470 case PointerGesture::Mode::PRESS:
2471 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 // Unfade the pointer when the current gesture manipulates the
2473 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002474 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 break;
Michael Wright227c5542020-07-02 18:30:52 +01002476 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002477 // Fade the pointer when the current gesture manipulates a different
2478 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002479 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002480 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002481 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002482 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483 }
2484 break;
2485 }
2486
2487 // Send events!
2488 int32_t metaState = getContext()->getGlobalMetaState();
2489 int32_t buttonState = mCurrentCookedState.buttonState;
2490
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002491 uint32_t flags = 0;
2492
2493 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2494 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2495 }
2496
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497 // Update last coordinates of pointers that have moved so that we observe the new
2498 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002499 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2500 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2501 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2502 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2503 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2504 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002505 bool moveNeeded = false;
2506 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2507 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2508 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2509 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2510 mPointerGesture.lastGestureIdBits.value);
2511 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2512 mPointerGesture.currentGestureCoords,
2513 mPointerGesture.currentGestureIdToIndex,
2514 mPointerGesture.lastGestureProperties,
2515 mPointerGesture.lastGestureCoords,
2516 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2517 if (buttonState != mLastCookedState.buttonState) {
2518 moveNeeded = true;
2519 }
2520 }
2521
2522 // Send motion events for all pointers that went up or were canceled.
2523 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2524 if (!dispatchedGestureIdBits.isEmpty()) {
2525 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002526 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2527 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2529 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2530 mPointerGesture.downTime);
2531
2532 dispatchedGestureIdBits.clear();
2533 } else {
2534 BitSet32 upGestureIdBits;
2535 if (finishPreviousGesture) {
2536 upGestureIdBits = dispatchedGestureIdBits;
2537 } else {
2538 upGestureIdBits.value =
2539 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2540 }
2541 while (!upGestureIdBits.isEmpty()) {
2542 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2543
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002544 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002545 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002546 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002547 mPointerGesture.lastGestureCoords,
2548 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2549 0, mPointerGesture.downTime);
2550
2551 dispatchedGestureIdBits.clearBit(id);
2552 }
2553 }
2554 }
2555
2556 // Send motion events for all pointers that moved.
2557 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002558 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002559 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002560 mPointerGesture.currentGestureProperties,
2561 mPointerGesture.currentGestureCoords,
2562 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2563 mPointerGesture.downTime);
2564 }
2565
2566 // Send motion events for all pointers that went down.
2567 if (down) {
2568 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2569 ~dispatchedGestureIdBits.value);
2570 while (!downGestureIdBits.isEmpty()) {
2571 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2572 dispatchedGestureIdBits.markBit(id);
2573
2574 if (dispatchedGestureIdBits.count() == 1) {
2575 mPointerGesture.downTime = when;
2576 }
2577
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002578 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002579 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002580 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002581 mPointerGesture.currentGestureCoords,
2582 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2583 0, mPointerGesture.downTime);
2584 }
2585 }
2586
2587 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002588 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002589 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2590 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591 mPointerGesture.currentGestureProperties,
2592 mPointerGesture.currentGestureCoords,
2593 mPointerGesture.currentGestureIdToIndex,
2594 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2595 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2596 // Synthesize a hover move event after all pointers go up to indicate that
2597 // the pointer is hovering again even if the user is not currently touching
2598 // the touch pad. This ensures that a view will receive a fresh hover enter
2599 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002600 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002601
2602 PointerProperties pointerProperties;
2603 pointerProperties.clear();
2604 pointerProperties.id = 0;
2605 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2606
2607 PointerCoords pointerCoords;
2608 pointerCoords.clear();
2609 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2610 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2611
2612 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002613 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002614 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002615 metaState, buttonState, MotionClassification::NONE,
2616 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2617 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002618 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002619 }
2620
2621 // Update state.
2622 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2623 if (!down) {
2624 mPointerGesture.lastGestureIdBits.clear();
2625 } else {
2626 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2627 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2628 uint32_t id = idBits.clearFirstMarkedBit();
2629 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2630 mPointerGesture.lastGestureProperties[index].copyFrom(
2631 mPointerGesture.currentGestureProperties[index]);
2632 mPointerGesture.lastGestureCoords[index].copyFrom(
2633 mPointerGesture.currentGestureCoords[index]);
2634 mPointerGesture.lastGestureIdToIndex[id] = index;
2635 }
2636 }
2637}
2638
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002639void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002640 // Cancel previously dispatches pointers.
2641 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2642 int32_t metaState = getContext()->getGlobalMetaState();
2643 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002644 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2645 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002646 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2647 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2648 0, 0, mPointerGesture.downTime);
2649 }
2650
2651 // Reset the current pointer gesture.
2652 mPointerGesture.reset();
2653 mPointerVelocityControl.reset();
2654
2655 // Remove any current spots.
2656 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002657 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002658 mPointerController->clearSpots();
2659 }
2660}
2661
2662bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2663 bool* outFinishPreviousGesture, bool isTimeout) {
2664 *outCancelPreviousGesture = false;
2665 *outFinishPreviousGesture = false;
2666
2667 // Handle TAP timeout.
2668 if (isTimeout) {
2669#if DEBUG_GESTURES
2670 ALOGD("Gestures: Processing timeout");
2671#endif
2672
Michael Wright227c5542020-07-02 18:30:52 +01002673 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002674 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2675 // The tap/drag timeout has not yet expired.
2676 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2677 mConfig.pointerGestureTapDragInterval);
2678 } else {
2679 // The tap is finished.
2680#if DEBUG_GESTURES
2681 ALOGD("Gestures: TAP finished");
2682#endif
2683 *outFinishPreviousGesture = true;
2684
2685 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002686 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002687 mPointerGesture.currentGestureIdBits.clear();
2688
2689 mPointerVelocityControl.reset();
2690 return true;
2691 }
2692 }
2693
2694 // We did not handle this timeout.
2695 return false;
2696 }
2697
2698 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2699 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2700
2701 // Update the velocity tracker.
2702 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002703 std::vector<VelocityTracker::Position> positions;
2704 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002705 uint32_t id = idBits.clearFirstMarkedBit();
2706 const RawPointerData::Pointer& pointer =
2707 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002708 float x = pointer.x * mPointerXMovementScale;
2709 float y = pointer.y * mPointerYMovementScale;
2710 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002711 }
2712 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2713 positions);
2714 }
2715
2716 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2717 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002718 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2719 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2720 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002721 mPointerGesture.resetTap();
2722 }
2723
2724 // Pick a new active touch id if needed.
2725 // Choose an arbitrary pointer that just went down, if there is one.
2726 // Otherwise choose an arbitrary remaining pointer.
2727 // This guarantees we always have an active touch id when there is at least one pointer.
2728 // We keep the same active touch id for as long as possible.
2729 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2730 int32_t activeTouchId = lastActiveTouchId;
2731 if (activeTouchId < 0) {
2732 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2733 activeTouchId = mPointerGesture.activeTouchId =
2734 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2735 mPointerGesture.firstTouchTime = when;
2736 }
2737 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2738 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2739 activeTouchId = mPointerGesture.activeTouchId =
2740 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2741 } else {
2742 activeTouchId = mPointerGesture.activeTouchId = -1;
2743 }
2744 }
2745
2746 // Determine whether we are in quiet time.
2747 bool isQuietTime = false;
2748 if (activeTouchId < 0) {
2749 mPointerGesture.resetQuietTime();
2750 } else {
2751 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2752 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002753 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2754 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2755 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002756 currentFingerCount < 2) {
2757 // Enter quiet time when exiting swipe or freeform state.
2758 // This is to prevent accidentally entering the hover state and flinging the
2759 // pointer when finishing a swipe and there is still one pointer left onscreen.
2760 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002761 } else if (mPointerGesture.lastGestureMode ==
2762 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002763 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2764 // Enter quiet time when releasing the button and there are still two or more
2765 // fingers down. This may indicate that one finger was used to press the button
2766 // but it has not gone up yet.
2767 isQuietTime = true;
2768 }
2769 if (isQuietTime) {
2770 mPointerGesture.quietTime = when;
2771 }
2772 }
2773 }
2774
2775 // Switch states based on button and pointer state.
2776 if (isQuietTime) {
2777 // Case 1: Quiet time. (QUIET)
2778#if DEBUG_GESTURES
2779 ALOGD("Gestures: QUIET for next %0.3fms",
2780 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2781#endif
Michael Wright227c5542020-07-02 18:30:52 +01002782 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002783 *outFinishPreviousGesture = true;
2784 }
2785
2786 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002787 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 mPointerGesture.currentGestureIdBits.clear();
2789
2790 mPointerVelocityControl.reset();
2791 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2792 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2793 // The pointer follows the active touch point.
2794 // Emit DOWN, MOVE, UP events at the pointer location.
2795 //
2796 // Only the active touch matters; other fingers are ignored. This policy helps
2797 // to handle the case where the user places a second finger on the touch pad
2798 // to apply the necessary force to depress an integrated button below the surface.
2799 // We don't want the second finger to be delivered to applications.
2800 //
2801 // For this to work well, we need to make sure to track the pointer that is really
2802 // active. If the user first puts one finger down to click then adds another
2803 // finger to drag then the active pointer should switch to the finger that is
2804 // being dragged.
2805#if DEBUG_GESTURES
2806 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2807 "currentFingerCount=%d",
2808 activeTouchId, currentFingerCount);
2809#endif
2810 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002811 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002812 *outFinishPreviousGesture = true;
2813 mPointerGesture.activeGestureId = 0;
2814 }
2815
2816 // Switch pointers if needed.
2817 // Find the fastest pointer and follow it.
2818 if (activeTouchId >= 0 && currentFingerCount > 1) {
2819 int32_t bestId = -1;
2820 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2821 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2822 uint32_t id = idBits.clearFirstMarkedBit();
2823 float vx, vy;
2824 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2825 float speed = hypotf(vx, vy);
2826 if (speed > bestSpeed) {
2827 bestId = id;
2828 bestSpeed = speed;
2829 }
2830 }
2831 }
2832 if (bestId >= 0 && bestId != activeTouchId) {
2833 mPointerGesture.activeTouchId = activeTouchId = bestId;
2834#if DEBUG_GESTURES
2835 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2836 "bestId=%d, bestSpeed=%0.3f",
2837 bestId, bestSpeed);
2838#endif
2839 }
2840 }
2841
2842 float deltaX = 0, deltaY = 0;
2843 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2844 const RawPointerData::Pointer& currentPointer =
2845 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2846 const RawPointerData::Pointer& lastPointer =
2847 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2848 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2849 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2850
2851 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2852 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2853
2854 // Move the pointer using a relative motion.
2855 // When using spots, the click will occur at the position of the anchor
2856 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002857 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002858 } else {
2859 mPointerVelocityControl.reset();
2860 }
2861
Prabir Pradhand7482e72021-03-09 13:54:55 -08002862 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002863
Michael Wright227c5542020-07-02 18:30:52 +01002864 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 mPointerGesture.currentGestureIdBits.clear();
2866 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2867 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2868 mPointerGesture.currentGestureProperties[0].clear();
2869 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2870 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2871 mPointerGesture.currentGestureCoords[0].clear();
2872 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2873 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2874 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2875 } else if (currentFingerCount == 0) {
2876 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002877 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878 *outFinishPreviousGesture = true;
2879 }
2880
2881 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2882 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2883 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002884 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2885 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886 lastFingerCount == 1) {
2887 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002888 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002889 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2890 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2891#if DEBUG_GESTURES
2892 ALOGD("Gestures: TAP");
2893#endif
2894
2895 mPointerGesture.tapUpTime = when;
2896 getContext()->requestTimeoutAtTime(when +
2897 mConfig.pointerGestureTapDragInterval);
2898
2899 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002900 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002901 mPointerGesture.currentGestureIdBits.clear();
2902 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2903 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2904 mPointerGesture.currentGestureProperties[0].clear();
2905 mPointerGesture.currentGestureProperties[0].id =
2906 mPointerGesture.activeGestureId;
2907 mPointerGesture.currentGestureProperties[0].toolType =
2908 AMOTION_EVENT_TOOL_TYPE_FINGER;
2909 mPointerGesture.currentGestureCoords[0].clear();
2910 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2911 mPointerGesture.tapX);
2912 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2913 mPointerGesture.tapY);
2914 mPointerGesture.currentGestureCoords[0]
2915 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2916
2917 tapped = true;
2918 } else {
2919#if DEBUG_GESTURES
2920 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2921 y - mPointerGesture.tapY);
2922#endif
2923 }
2924 } else {
2925#if DEBUG_GESTURES
2926 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2927 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2928 (when - mPointerGesture.tapDownTime) * 0.000001f);
2929 } else {
2930 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2931 }
2932#endif
2933 }
2934 }
2935
2936 mPointerVelocityControl.reset();
2937
2938 if (!tapped) {
2939#if DEBUG_GESTURES
2940 ALOGD("Gestures: NEUTRAL");
2941#endif
2942 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002943 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 mPointerGesture.currentGestureIdBits.clear();
2945 }
2946 } else if (currentFingerCount == 1) {
2947 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2948 // The pointer follows the active touch point.
2949 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2950 // When in TAP_DRAG, emit MOVE events at the pointer location.
2951 ALOG_ASSERT(activeTouchId >= 0);
2952
Michael Wright227c5542020-07-02 18:30:52 +01002953 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2954 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002955 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002956 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002957 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2958 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002959 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002960 } else {
2961#if DEBUG_GESTURES
2962 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2963 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2964#endif
2965 }
2966 } else {
2967#if DEBUG_GESTURES
2968 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2969 (when - mPointerGesture.tapUpTime) * 0.000001f);
2970#endif
2971 }
Michael Wright227c5542020-07-02 18:30:52 +01002972 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2973 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974 }
2975
2976 float deltaX = 0, deltaY = 0;
2977 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2978 const RawPointerData::Pointer& currentPointer =
2979 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2980 const RawPointerData::Pointer& lastPointer =
2981 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2982 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2983 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2984
2985 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2986 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2987
2988 // Move the pointer using a relative motion.
2989 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002990 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 } else {
2992 mPointerVelocityControl.reset();
2993 }
2994
2995 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002996 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997#if DEBUG_GESTURES
2998 ALOGD("Gestures: TAP_DRAG");
2999#endif
3000 down = true;
3001 } else {
3002#if DEBUG_GESTURES
3003 ALOGD("Gestures: HOVER");
3004#endif
Michael Wright227c5542020-07-02 18:30:52 +01003005 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003006 *outFinishPreviousGesture = true;
3007 }
3008 mPointerGesture.activeGestureId = 0;
3009 down = false;
3010 }
3011
Prabir Pradhand7482e72021-03-09 13:54:55 -08003012 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003013
3014 mPointerGesture.currentGestureIdBits.clear();
3015 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3016 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3017 mPointerGesture.currentGestureProperties[0].clear();
3018 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3019 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3020 mPointerGesture.currentGestureCoords[0].clear();
3021 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3022 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3023 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3024 down ? 1.0f : 0.0f);
3025
3026 if (lastFingerCount == 0 && currentFingerCount != 0) {
3027 mPointerGesture.resetTap();
3028 mPointerGesture.tapDownTime = when;
3029 mPointerGesture.tapX = x;
3030 mPointerGesture.tapY = y;
3031 }
3032 } else {
3033 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3034 // We need to provide feedback for each finger that goes down so we cannot wait
3035 // for the fingers to move before deciding what to do.
3036 //
3037 // The ambiguous case is deciding what to do when there are two fingers down but they
3038 // have not moved enough to determine whether they are part of a drag or part of a
3039 // freeform gesture, or just a press or long-press at the pointer location.
3040 //
3041 // When there are two fingers we start with the PRESS hypothesis and we generate a
3042 // down at the pointer location.
3043 //
3044 // When the two fingers move enough or when additional fingers are added, we make
3045 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3046 ALOG_ASSERT(activeTouchId >= 0);
3047
3048 bool settled = when >=
3049 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003050 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3051 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3052 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003053 *outFinishPreviousGesture = true;
3054 } else if (!settled && currentFingerCount > lastFingerCount) {
3055 // Additional pointers have gone down but not yet settled.
3056 // Reset the gesture.
3057#if DEBUG_GESTURES
3058 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3059 "settle time remaining %0.3fms",
3060 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3061 when) * 0.000001f);
3062#endif
3063 *outCancelPreviousGesture = true;
3064 } else {
3065 // Continue previous gesture.
3066 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3067 }
3068
3069 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003070 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003071 mPointerGesture.activeGestureId = 0;
3072 mPointerGesture.referenceIdBits.clear();
3073 mPointerVelocityControl.reset();
3074
3075 // Use the centroid and pointer location as the reference points for the gesture.
3076#if DEBUG_GESTURES
3077 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3078 "settle time remaining %0.3fms",
3079 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3080 when) * 0.000001f);
3081#endif
3082 mCurrentRawState.rawPointerData
3083 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3084 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003085 auto [x, y] = getMouseCursorPosition();
3086 mPointerGesture.referenceGestureX = x;
3087 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003088 }
3089
3090 // Clear the reference deltas for fingers not yet included in the reference calculation.
3091 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3092 ~mPointerGesture.referenceIdBits.value);
3093 !idBits.isEmpty();) {
3094 uint32_t id = idBits.clearFirstMarkedBit();
3095 mPointerGesture.referenceDeltas[id].dx = 0;
3096 mPointerGesture.referenceDeltas[id].dy = 0;
3097 }
3098 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3099
3100 // Add delta for all fingers and calculate a common movement delta.
3101 float commonDeltaX = 0, commonDeltaY = 0;
3102 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3103 mCurrentCookedState.fingerIdBits.value);
3104 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3105 bool first = (idBits == commonIdBits);
3106 uint32_t id = idBits.clearFirstMarkedBit();
3107 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3108 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3109 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3110 delta.dx += cpd.x - lpd.x;
3111 delta.dy += cpd.y - lpd.y;
3112
3113 if (first) {
3114 commonDeltaX = delta.dx;
3115 commonDeltaY = delta.dy;
3116 } else {
3117 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3118 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3119 }
3120 }
3121
3122 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003123 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003124 float dist[MAX_POINTER_ID + 1];
3125 int32_t distOverThreshold = 0;
3126 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3127 uint32_t id = idBits.clearFirstMarkedBit();
3128 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3129 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3130 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3131 distOverThreshold += 1;
3132 }
3133 }
3134
3135 // Only transition when at least two pointers have moved further than
3136 // the minimum distance threshold.
3137 if (distOverThreshold >= 2) {
3138 if (currentFingerCount > 2) {
3139 // There are more than two pointers, switch to FREEFORM.
3140#if DEBUG_GESTURES
3141 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3142 currentFingerCount);
3143#endif
3144 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003145 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003146 } else {
3147 // There are exactly two pointers.
3148 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3149 uint32_t id1 = idBits.clearFirstMarkedBit();
3150 uint32_t id2 = idBits.firstMarkedBit();
3151 const RawPointerData::Pointer& p1 =
3152 mCurrentRawState.rawPointerData.pointerForId(id1);
3153 const RawPointerData::Pointer& p2 =
3154 mCurrentRawState.rawPointerData.pointerForId(id2);
3155 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3156 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3157 // There are two pointers but they are too far apart for a SWIPE,
3158 // switch to FREEFORM.
3159#if DEBUG_GESTURES
3160 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3161 mutualDistance, mPointerGestureMaxSwipeWidth);
3162#endif
3163 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003164 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003165 } else {
3166 // There are two pointers. Wait for both pointers to start moving
3167 // before deciding whether this is a SWIPE or FREEFORM gesture.
3168 float dist1 = dist[id1];
3169 float dist2 = dist[id2];
3170 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3171 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3172 // Calculate the dot product of the displacement vectors.
3173 // When the vectors are oriented in approximately the same direction,
3174 // the angle betweeen them is near zero and the cosine of the angle
3175 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3176 // mag(v2).
3177 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3178 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3179 float dx1 = delta1.dx * mPointerXZoomScale;
3180 float dy1 = delta1.dy * mPointerYZoomScale;
3181 float dx2 = delta2.dx * mPointerXZoomScale;
3182 float dy2 = delta2.dy * mPointerYZoomScale;
3183 float dot = dx1 * dx2 + dy1 * dy2;
3184 float cosine = dot / (dist1 * dist2); // denominator always > 0
3185 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3186 // Pointers are moving in the same direction. Switch to SWIPE.
3187#if DEBUG_GESTURES
3188 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3189 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3190 "cosine %0.3f >= %0.3f",
3191 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3192 mConfig.pointerGestureMultitouchMinDistance, cosine,
3193 mConfig.pointerGestureSwipeTransitionAngleCosine);
3194#endif
Michael Wright227c5542020-07-02 18:30:52 +01003195 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003196 } else {
3197 // Pointers are moving in different directions. Switch to FREEFORM.
3198#if DEBUG_GESTURES
3199 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3200 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3201 "cosine %0.3f < %0.3f",
3202 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3203 mConfig.pointerGestureMultitouchMinDistance, cosine,
3204 mConfig.pointerGestureSwipeTransitionAngleCosine);
3205#endif
3206 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003207 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003208 }
3209 }
3210 }
3211 }
3212 }
Michael Wright227c5542020-07-02 18:30:52 +01003213 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003214 // Switch from SWIPE to FREEFORM if additional pointers go down.
3215 // Cancel previous gesture.
3216 if (currentFingerCount > 2) {
3217#if DEBUG_GESTURES
3218 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3219 currentFingerCount);
3220#endif
3221 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003222 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003223 }
3224 }
3225
3226 // Move the reference points based on the overall group motion of the fingers
3227 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003228 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003229 (commonDeltaX || commonDeltaY)) {
3230 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3231 uint32_t id = idBits.clearFirstMarkedBit();
3232 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3233 delta.dx = 0;
3234 delta.dy = 0;
3235 }
3236
3237 mPointerGesture.referenceTouchX += commonDeltaX;
3238 mPointerGesture.referenceTouchY += commonDeltaY;
3239
3240 commonDeltaX *= mPointerXMovementScale;
3241 commonDeltaY *= mPointerYMovementScale;
3242
3243 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3244 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3245
3246 mPointerGesture.referenceGestureX += commonDeltaX;
3247 mPointerGesture.referenceGestureY += commonDeltaY;
3248 }
3249
3250 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003251 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3252 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003253 // PRESS or SWIPE mode.
3254#if DEBUG_GESTURES
3255 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3256 "activeGestureId=%d, currentTouchPointerCount=%d",
3257 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3258#endif
3259 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3260
3261 mPointerGesture.currentGestureIdBits.clear();
3262 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3263 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3264 mPointerGesture.currentGestureProperties[0].clear();
3265 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3266 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3267 mPointerGesture.currentGestureCoords[0].clear();
3268 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3269 mPointerGesture.referenceGestureX);
3270 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3271 mPointerGesture.referenceGestureY);
3272 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003273 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003274 // FREEFORM mode.
3275#if DEBUG_GESTURES
3276 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3277 "activeGestureId=%d, currentTouchPointerCount=%d",
3278 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3279#endif
3280 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3281
3282 mPointerGesture.currentGestureIdBits.clear();
3283
3284 BitSet32 mappedTouchIdBits;
3285 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003286 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003287 // Initially, assign the active gesture id to the active touch point
3288 // if there is one. No other touch id bits are mapped yet.
3289 if (!*outCancelPreviousGesture) {
3290 mappedTouchIdBits.markBit(activeTouchId);
3291 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3292 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3293 mPointerGesture.activeGestureId;
3294 } else {
3295 mPointerGesture.activeGestureId = -1;
3296 }
3297 } else {
3298 // Otherwise, assume we mapped all touches from the previous frame.
3299 // Reuse all mappings that are still applicable.
3300 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3301 mCurrentCookedState.fingerIdBits.value;
3302 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3303
3304 // Check whether we need to choose a new active gesture id because the
3305 // current went went up.
3306 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3307 ~mCurrentCookedState.fingerIdBits.value);
3308 !upTouchIdBits.isEmpty();) {
3309 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3310 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3311 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3312 mPointerGesture.activeGestureId = -1;
3313 break;
3314 }
3315 }
3316 }
3317
3318#if DEBUG_GESTURES
3319 ALOGD("Gestures: FREEFORM follow up "
3320 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3321 "activeGestureId=%d",
3322 mappedTouchIdBits.value, usedGestureIdBits.value,
3323 mPointerGesture.activeGestureId);
3324#endif
3325
3326 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3327 for (uint32_t i = 0; i < currentFingerCount; i++) {
3328 uint32_t touchId = idBits.clearFirstMarkedBit();
3329 uint32_t gestureId;
3330 if (!mappedTouchIdBits.hasBit(touchId)) {
3331 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3332 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3333#if DEBUG_GESTURES
3334 ALOGD("Gestures: FREEFORM "
3335 "new mapping for touch id %d -> gesture id %d",
3336 touchId, gestureId);
3337#endif
3338 } else {
3339 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3340#if DEBUG_GESTURES
3341 ALOGD("Gestures: FREEFORM "
3342 "existing mapping for touch id %d -> gesture id %d",
3343 touchId, gestureId);
3344#endif
3345 }
3346 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3347 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3348
3349 const RawPointerData::Pointer& pointer =
3350 mCurrentRawState.rawPointerData.pointerForId(touchId);
3351 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3352 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3353 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3354
3355 mPointerGesture.currentGestureProperties[i].clear();
3356 mPointerGesture.currentGestureProperties[i].id = gestureId;
3357 mPointerGesture.currentGestureProperties[i].toolType =
3358 AMOTION_EVENT_TOOL_TYPE_FINGER;
3359 mPointerGesture.currentGestureCoords[i].clear();
3360 mPointerGesture.currentGestureCoords[i]
3361 .setAxisValue(AMOTION_EVENT_AXIS_X,
3362 mPointerGesture.referenceGestureX + deltaX);
3363 mPointerGesture.currentGestureCoords[i]
3364 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3365 mPointerGesture.referenceGestureY + deltaY);
3366 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3367 1.0f);
3368 }
3369
3370 if (mPointerGesture.activeGestureId < 0) {
3371 mPointerGesture.activeGestureId =
3372 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3373#if DEBUG_GESTURES
3374 ALOGD("Gestures: FREEFORM new "
3375 "activeGestureId=%d",
3376 mPointerGesture.activeGestureId);
3377#endif
3378 }
3379 }
3380 }
3381
3382 mPointerController->setButtonState(mCurrentRawState.buttonState);
3383
3384#if DEBUG_GESTURES
3385 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3386 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3387 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3388 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3389 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3390 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3391 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3392 uint32_t id = idBits.clearFirstMarkedBit();
3393 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3394 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3395 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3396 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3397 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3398 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3399 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3400 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3401 }
3402 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3403 uint32_t id = idBits.clearFirstMarkedBit();
3404 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3405 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3406 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3407 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3408 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3409 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3410 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3411 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3412 }
3413#endif
3414 return true;
3415}
3416
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003417void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003418 mPointerSimple.currentCoords.clear();
3419 mPointerSimple.currentProperties.clear();
3420
3421 bool down, hovering;
3422 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3423 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3424 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003425 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3426 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003427
3428 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3429 down = !hovering;
3430
Prabir Pradhand7482e72021-03-09 13:54:55 -08003431 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003432 mPointerSimple.currentCoords.copyFrom(
3433 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3434 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3435 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3436 mPointerSimple.currentProperties.id = 0;
3437 mPointerSimple.currentProperties.toolType =
3438 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3439 } else {
3440 down = false;
3441 hovering = false;
3442 }
3443
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003444 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003445}
3446
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003447void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3448 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003449}
3450
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003451void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003452 mPointerSimple.currentCoords.clear();
3453 mPointerSimple.currentProperties.clear();
3454
3455 bool down, hovering;
3456 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3457 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3458 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3459 float deltaX = 0, deltaY = 0;
3460 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3461 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3462 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3463 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3464 mPointerXMovementScale;
3465 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3466 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3467 mPointerYMovementScale;
3468
3469 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3470 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3471
Prabir Pradhand7482e72021-03-09 13:54:55 -08003472 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003473 } else {
3474 mPointerVelocityControl.reset();
3475 }
3476
3477 down = isPointerDown(mCurrentRawState.buttonState);
3478 hovering = !down;
3479
Prabir Pradhand7482e72021-03-09 13:54:55 -08003480 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003481 mPointerSimple.currentCoords.copyFrom(
3482 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3483 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3484 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3485 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3486 hovering ? 0.0f : 1.0f);
3487 mPointerSimple.currentProperties.id = 0;
3488 mPointerSimple.currentProperties.toolType =
3489 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3490 } else {
3491 mPointerVelocityControl.reset();
3492
3493 down = false;
3494 hovering = false;
3495 }
3496
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003497 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003498}
3499
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003500void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3501 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003502
3503 mPointerVelocityControl.reset();
3504}
3505
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003506void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3507 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003508 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509
3510 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003511 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003512 mPointerController->clearSpots();
3513 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003514 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003516 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517 }
Garfield Tan9514d782020-11-10 16:37:23 -08003518 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003519
Prabir Pradhand7482e72021-03-09 13:54:55 -08003520 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003521
3522 if (mPointerSimple.down && !down) {
3523 mPointerSimple.down = false;
3524
3525 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003526 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3527 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003528 mLastRawState.buttonState, MotionClassification::NONE,
3529 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3530 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3531 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3532 /* videoFrames */ {});
3533 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003534 }
3535
3536 if (mPointerSimple.hovering && !hovering) {
3537 mPointerSimple.hovering = false;
3538
3539 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003540 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3541 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3542 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003543 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3544 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3545 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3546 /* videoFrames */ {});
3547 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003548 }
3549
3550 if (down) {
3551 if (!mPointerSimple.down) {
3552 mPointerSimple.down = true;
3553 mPointerSimple.downTime = when;
3554
3555 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003556 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003557 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3558 metaState, mCurrentRawState.buttonState,
3559 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3560 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3561 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3562 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3563 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003564 }
3565
3566 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003567 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3568 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003569 mCurrentRawState.buttonState, MotionClassification::NONE,
3570 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3571 &mPointerSimple.currentCoords, mOrientedXPrecision,
3572 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3573 mPointerSimple.downTime, /* videoFrames */ {});
3574 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003575 }
3576
3577 if (hovering) {
3578 if (!mPointerSimple.hovering) {
3579 mPointerSimple.hovering = true;
3580
3581 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003582 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003583 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3584 metaState, mCurrentRawState.buttonState,
3585 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3586 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3587 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3588 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3589 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590 }
3591
3592 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003593 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3594 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3595 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003596 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3597 &mPointerSimple.currentCoords, mOrientedXPrecision,
3598 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3599 mPointerSimple.downTime, /* videoFrames */ {});
3600 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003601 }
3602
3603 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3604 float vscroll = mCurrentRawState.rawVScroll;
3605 float hscroll = mCurrentRawState.rawHScroll;
3606 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3607 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3608
3609 // Send scroll.
3610 PointerCoords pointerCoords;
3611 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3612 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3613 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3614
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003615 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3616 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003617 mCurrentRawState.buttonState, MotionClassification::NONE,
3618 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3619 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3620 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3621 /* videoFrames */ {});
3622 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003623 }
3624
3625 // Save state.
3626 if (down || hovering) {
3627 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3628 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3629 } else {
3630 mPointerSimple.reset();
3631 }
3632}
3633
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003634void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003635 mPointerSimple.currentCoords.clear();
3636 mPointerSimple.currentProperties.clear();
3637
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003638 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003639}
3640
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003641void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3642 uint32_t source, int32_t action, int32_t actionButton,
3643 int32_t flags, int32_t metaState, int32_t buttonState,
3644 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003645 const PointerCoords* coords, const uint32_t* idToIndex,
3646 BitSet32 idBits, int32_t changedId, float xPrecision,
3647 float yPrecision, nsecs_t downTime) {
3648 PointerCoords pointerCoords[MAX_POINTERS];
3649 PointerProperties pointerProperties[MAX_POINTERS];
3650 uint32_t pointerCount = 0;
3651 while (!idBits.isEmpty()) {
3652 uint32_t id = idBits.clearFirstMarkedBit();
3653 uint32_t index = idToIndex[id];
3654 pointerProperties[pointerCount].copyFrom(properties[index]);
3655 pointerCoords[pointerCount].copyFrom(coords[index]);
3656
3657 if (changedId >= 0 && id == uint32_t(changedId)) {
3658 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3659 }
3660
3661 pointerCount += 1;
3662 }
3663
3664 ALOG_ASSERT(pointerCount != 0);
3665
3666 if (changedId >= 0 && pointerCount == 1) {
3667 // Replace initial down and final up action.
3668 // We can compare the action without masking off the changed pointer index
3669 // because we know the index is 0.
3670 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3671 action = AMOTION_EVENT_ACTION_DOWN;
3672 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003673 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3674 action = AMOTION_EVENT_ACTION_CANCEL;
3675 } else {
3676 action = AMOTION_EVENT_ACTION_UP;
3677 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003678 } else {
3679 // Can't happen.
3680 ALOG_ASSERT(false);
3681 }
3682 }
3683 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3684 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003685 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003686 auto [x, y] = getMouseCursorPosition();
3687 xCursorPosition = x;
3688 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003689 }
3690 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3691 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003692 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003693 std::for_each(frames.begin(), frames.end(),
3694 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003695 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3696 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003697 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3698 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3699 downTime, std::move(frames));
3700 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003701}
3702
3703bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3704 const PointerCoords* inCoords,
3705 const uint32_t* inIdToIndex,
3706 PointerProperties* outProperties,
3707 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3708 BitSet32 idBits) const {
3709 bool changed = false;
3710 while (!idBits.isEmpty()) {
3711 uint32_t id = idBits.clearFirstMarkedBit();
3712 uint32_t inIndex = inIdToIndex[id];
3713 uint32_t outIndex = outIdToIndex[id];
3714
3715 const PointerProperties& curInProperties = inProperties[inIndex];
3716 const PointerCoords& curInCoords = inCoords[inIndex];
3717 PointerProperties& curOutProperties = outProperties[outIndex];
3718 PointerCoords& curOutCoords = outCoords[outIndex];
3719
3720 if (curInProperties != curOutProperties) {
3721 curOutProperties.copyFrom(curInProperties);
3722 changed = true;
3723 }
3724
3725 if (curInCoords != curOutCoords) {
3726 curOutCoords.copyFrom(curInCoords);
3727 changed = true;
3728 }
3729 }
3730 return changed;
3731}
3732
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003733void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3734 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3735 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003736}
3737
Arthur Hung4197f6b2020-03-16 15:39:59 +08003738// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003739void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003740 // Scale to surface coordinate.
3741 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3742 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3743
arthurhunga36b28e2020-12-29 20:28:15 +08003744 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3745 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3746
Arthur Hung4197f6b2020-03-16 15:39:59 +08003747 // Rotate to surface coordinate.
3748 // 0 - no swap and reverse.
3749 // 90 - swap x/y and reverse y.
3750 // 180 - reverse x, y.
3751 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003752 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003753 case DISPLAY_ORIENTATION_0:
3754 x = xScaled + mXTranslate;
3755 y = yScaled + mYTranslate;
3756 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003757 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003758 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003759 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003760 break;
3761 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003762 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3763 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003764 break;
3765 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003766 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003767 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003768 break;
3769 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003770 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003771 }
3772}
3773
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003774bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003775 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3776 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3777
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003778 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003779 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003780 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003781 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003782}
3783
3784const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3785 for (const VirtualKey& virtualKey : mVirtualKeys) {
3786#if DEBUG_VIRTUAL_KEYS
3787 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3788 "left=%d, top=%d, right=%d, bottom=%d",
3789 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3790 virtualKey.hitRight, virtualKey.hitBottom);
3791#endif
3792
3793 if (virtualKey.isHit(x, y)) {
3794 return &virtualKey;
3795 }
3796 }
3797
3798 return nullptr;
3799}
3800
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003801void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3802 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3803 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003804
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003805 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003806
3807 if (currentPointerCount == 0) {
3808 // No pointers to assign.
3809 return;
3810 }
3811
3812 if (lastPointerCount == 0) {
3813 // All pointers are new.
3814 for (uint32_t i = 0; i < currentPointerCount; i++) {
3815 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003816 current.rawPointerData.pointers[i].id = id;
3817 current.rawPointerData.idToIndex[id] = i;
3818 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003819 }
3820 return;
3821 }
3822
3823 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003824 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003825 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003826 uint32_t id = last.rawPointerData.pointers[0].id;
3827 current.rawPointerData.pointers[0].id = id;
3828 current.rawPointerData.idToIndex[id] = 0;
3829 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003830 return;
3831 }
3832
3833 // General case.
3834 // We build a heap of squared euclidean distances between current and last pointers
3835 // associated with the current and last pointer indices. Then, we find the best
3836 // match (by distance) for each current pointer.
3837 // The pointers must have the same tool type but it is possible for them to
3838 // transition from hovering to touching or vice-versa while retaining the same id.
3839 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3840
3841 uint32_t heapSize = 0;
3842 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3843 currentPointerIndex++) {
3844 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3845 lastPointerIndex++) {
3846 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003847 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003848 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003849 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003850 if (currentPointer.toolType == lastPointer.toolType) {
3851 int64_t deltaX = currentPointer.x - lastPointer.x;
3852 int64_t deltaY = currentPointer.y - lastPointer.y;
3853
3854 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3855
3856 // Insert new element into the heap (sift up).
3857 heap[heapSize].currentPointerIndex = currentPointerIndex;
3858 heap[heapSize].lastPointerIndex = lastPointerIndex;
3859 heap[heapSize].distance = distance;
3860 heapSize += 1;
3861 }
3862 }
3863 }
3864
3865 // Heapify
3866 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3867 startIndex -= 1;
3868 for (uint32_t parentIndex = startIndex;;) {
3869 uint32_t childIndex = parentIndex * 2 + 1;
3870 if (childIndex >= heapSize) {
3871 break;
3872 }
3873
3874 if (childIndex + 1 < heapSize &&
3875 heap[childIndex + 1].distance < heap[childIndex].distance) {
3876 childIndex += 1;
3877 }
3878
3879 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3880 break;
3881 }
3882
3883 swap(heap[parentIndex], heap[childIndex]);
3884 parentIndex = childIndex;
3885 }
3886 }
3887
3888#if DEBUG_POINTER_ASSIGNMENT
3889 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3890 for (size_t i = 0; i < heapSize; i++) {
3891 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3892 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3893 }
3894#endif
3895
3896 // Pull matches out by increasing order of distance.
3897 // To avoid reassigning pointers that have already been matched, the loop keeps track
3898 // of which last and current pointers have been matched using the matchedXXXBits variables.
3899 // It also tracks the used pointer id bits.
3900 BitSet32 matchedLastBits(0);
3901 BitSet32 matchedCurrentBits(0);
3902 BitSet32 usedIdBits(0);
3903 bool first = true;
3904 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3905 while (heapSize > 0) {
3906 if (first) {
3907 // The first time through the loop, we just consume the root element of
3908 // the heap (the one with smallest distance).
3909 first = false;
3910 } else {
3911 // Previous iterations consumed the root element of the heap.
3912 // Pop root element off of the heap (sift down).
3913 heap[0] = heap[heapSize];
3914 for (uint32_t parentIndex = 0;;) {
3915 uint32_t childIndex = parentIndex * 2 + 1;
3916 if (childIndex >= heapSize) {
3917 break;
3918 }
3919
3920 if (childIndex + 1 < heapSize &&
3921 heap[childIndex + 1].distance < heap[childIndex].distance) {
3922 childIndex += 1;
3923 }
3924
3925 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3926 break;
3927 }
3928
3929 swap(heap[parentIndex], heap[childIndex]);
3930 parentIndex = childIndex;
3931 }
3932
3933#if DEBUG_POINTER_ASSIGNMENT
3934 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003935 for (size_t j = 0; j < heapSize; j++) {
3936 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3937 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003938 }
3939#endif
3940 }
3941
3942 heapSize -= 1;
3943
3944 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3945 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3946
3947 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3948 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3949
3950 matchedCurrentBits.markBit(currentPointerIndex);
3951 matchedLastBits.markBit(lastPointerIndex);
3952
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003953 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3954 current.rawPointerData.pointers[currentPointerIndex].id = id;
3955 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3956 current.rawPointerData.markIdBit(id,
3957 current.rawPointerData.isHovering(
3958 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003959 usedIdBits.markBit(id);
3960
3961#if DEBUG_POINTER_ASSIGNMENT
3962 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3963 ", distance=%" PRIu64,
3964 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3965#endif
3966 break;
3967 }
3968 }
3969
3970 // Assign fresh ids to pointers that were not matched in the process.
3971 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3972 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3973 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3974
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003975 current.rawPointerData.pointers[currentPointerIndex].id = id;
3976 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3977 current.rawPointerData.markIdBit(id,
3978 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003979
3980#if DEBUG_POINTER_ASSIGNMENT
3981 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3982#endif
3983 }
3984}
3985
3986int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3987 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3988 return AKEY_STATE_VIRTUAL;
3989 }
3990
3991 for (const VirtualKey& virtualKey : mVirtualKeys) {
3992 if (virtualKey.keyCode == keyCode) {
3993 return AKEY_STATE_UP;
3994 }
3995 }
3996
3997 return AKEY_STATE_UNKNOWN;
3998}
3999
4000int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4001 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4002 return AKEY_STATE_VIRTUAL;
4003 }
4004
4005 for (const VirtualKey& virtualKey : mVirtualKeys) {
4006 if (virtualKey.scanCode == scanCode) {
4007 return AKEY_STATE_UP;
4008 }
4009 }
4010
4011 return AKEY_STATE_UNKNOWN;
4012}
4013
4014bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4015 const int32_t* keyCodes, uint8_t* outFlags) {
4016 for (const VirtualKey& virtualKey : mVirtualKeys) {
4017 for (size_t i = 0; i < numCodes; i++) {
4018 if (virtualKey.keyCode == keyCodes[i]) {
4019 outFlags[i] = 1;
4020 }
4021 }
4022 }
4023
4024 return true;
4025}
4026
4027std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4028 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004029 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004030 return std::make_optional(mPointerController->getDisplayId());
4031 } else {
4032 return std::make_optional(mViewport.displayId);
4033 }
4034 }
4035 return std::nullopt;
4036}
4037
Prabir Pradhand7482e72021-03-09 13:54:55 -08004038void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
4039 if (isPerWindowInputRotationEnabled()) {
4040 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4041 // space that is oriented with the viewport.
4042 rotateDelta(mViewport.orientation, &dx, &dy);
4043 }
4044
4045 mPointerController->move(dx, dy);
4046}
4047
4048std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4049 float x = 0;
4050 float y = 0;
4051 mPointerController->getPosition(&x, &y);
4052
4053 if (!isPerWindowInputRotationEnabled()) return {x, y};
4054 if (!mViewport.isValid()) return {x, y};
4055
4056 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4057 // to InputReader's un-rotated coordinate space.
4058 const int32_t orientation = getInverseRotation(mViewport.orientation);
4059 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4060 return {x, y};
4061}
4062
4063void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4064 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4065 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4066 // coordinate space that is oriented with the viewport.
4067 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4068 }
4069
4070 mPointerController->setPosition(x, y);
4071}
4072
4073void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4074 BitSet32 spotIdBits, int32_t displayId) {
4075 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4076
4077 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4078 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4079 float x = spotCoords[index].getX();
4080 float y = spotCoords[index].getY();
4081 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4082
4083 if (isPerWindowInputRotationEnabled()) {
4084 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4085 // coordinate space.
4086 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4087 }
4088
4089 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4090 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4091 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4092 }
4093
4094 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4095}
4096
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004097} // namespace android