blob: 1a7ddeef1308992ada86730b5cdaa4d0b51b3c5b [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
Chris Yea03dd232020-09-08 19:21:09 -070021#include <input/NamedEnum.h>
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070022#include "TouchInputMapper.h"
23
24#include "CursorButtonAccumulator.h"
25#include "CursorScrollAccumulator.h"
26#include "TouchButtonAccumulator.h"
27#include "TouchCursorInputMapperCommon.h"
28
29namespace android {
30
31// --- Constants ---
32
33// Maximum amount of latency to add to touch events while waiting for data from an
34// external stylus.
35static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
36
37// Maximum amount of time to wait on touch data before pushing out new pressure data.
38static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
39
40// Artificial latency on synthetic events created from stylus data without corresponding touch
41// data.
42static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
43
44// --- Static Definitions ---
45
46template <typename T>
47inline static void swap(T& a, T& b) {
48 T temp = a;
49 a = b;
50 b = temp;
51}
52
53static float calculateCommonVector(float a, float b) {
54 if (a > 0 && b > 0) {
55 return a < b ? a : b;
56 } else if (a < 0 && b < 0) {
57 return a > b ? a : b;
58 } else {
59 return 0;
60 }
61}
62
63inline static float distance(float x1, float y1, float x2, float y2) {
64 return hypotf(x1 - x2, y1 - y2);
65}
66
67inline static int32_t signExtendNybble(int32_t value) {
68 return value >= 8 ? value - 16 : value;
69}
70
71// --- RawPointerAxes ---
72
73RawPointerAxes::RawPointerAxes() {
74 clear();
75}
76
77void RawPointerAxes::clear() {
78 x.clear();
79 y.clear();
80 pressure.clear();
81 touchMajor.clear();
82 touchMinor.clear();
83 toolMajor.clear();
84 toolMinor.clear();
85 orientation.clear();
86 distance.clear();
87 tiltX.clear();
88 tiltY.clear();
89 trackingId.clear();
90 slot.clear();
91}
92
93// --- RawPointerData ---
94
95RawPointerData::RawPointerData() {
96 clear();
97}
98
99void RawPointerData::clear() {
100 pointerCount = 0;
101 clearIdBits();
102}
103
104void RawPointerData::copyFrom(const RawPointerData& other) {
105 pointerCount = other.pointerCount;
106 hoveringIdBits = other.hoveringIdBits;
107 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800108 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109
110 for (uint32_t i = 0; i < pointerCount; i++) {
111 pointers[i] = other.pointers[i];
112
113 int id = pointers[i].id;
114 idToIndex[id] = other.idToIndex[id];
115 }
116}
117
118void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
119 float x = 0, y = 0;
120 uint32_t count = touchingIdBits.count();
121 if (count) {
122 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
123 uint32_t id = idBits.clearFirstMarkedBit();
124 const Pointer& pointer = pointerForId(id);
125 x += pointer.x;
126 y += pointer.y;
127 }
128 x /= count;
129 y /= count;
130 }
131 *outX = x;
132 *outY = y;
133}
134
135// --- CookedPointerData ---
136
137CookedPointerData::CookedPointerData() {
138 clear();
139}
140
141void CookedPointerData::clear() {
142 pointerCount = 0;
143 hoveringIdBits.clear();
144 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800145 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000146 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700147}
148
149void CookedPointerData::copyFrom(const CookedPointerData& other) {
150 pointerCount = other.pointerCount;
151 hoveringIdBits = other.hoveringIdBits;
152 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000153 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700154
155 for (uint32_t i = 0; i < pointerCount; i++) {
156 pointerProperties[i].copyFrom(other.pointerProperties[i]);
157 pointerCoords[i].copyFrom(other.pointerCoords[i]);
158
159 int id = pointerProperties[i].id;
160 idToIndex[id] = other.idToIndex[id];
161 }
162}
163
164// --- TouchInputMapper ---
165
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800166TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
167 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700168 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100169 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800170 mRawSurfaceWidth(-1),
171 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700172 mSurfaceLeft(0),
173 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700174 mSurfaceRight(0),
175 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700176 mPhysicalWidth(-1),
177 mPhysicalHeight(-1),
178 mPhysicalLeft(0),
179 mPhysicalTop(0),
180 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
181
182TouchInputMapper::~TouchInputMapper() {}
183
184uint32_t TouchInputMapper::getSources() {
185 return mSource;
186}
187
188void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
189 InputMapper::populateDeviceInfo(info);
190
Michael Wright227c5542020-07-02 18:30:52 +0100191 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 info->addMotionRange(mOrientedRanges.x);
193 info->addMotionRange(mOrientedRanges.y);
194 info->addMotionRange(mOrientedRanges.pressure);
195
Chris Yef74dc422020-09-02 22:41:50 -0700196 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700197 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
198 //
199 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
200 // motion, i.e. the hardware dimensions, as the finger could move completely across the
201 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700202 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
203 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
204 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
205 x.fuzz, x.resolution);
206 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
207 y.fuzz, y.resolution);
208 }
209
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700210 if (mOrientedRanges.haveSize) {
211 info->addMotionRange(mOrientedRanges.size);
212 }
213
214 if (mOrientedRanges.haveTouchSize) {
215 info->addMotionRange(mOrientedRanges.touchMajor);
216 info->addMotionRange(mOrientedRanges.touchMinor);
217 }
218
219 if (mOrientedRanges.haveToolSize) {
220 info->addMotionRange(mOrientedRanges.toolMajor);
221 info->addMotionRange(mOrientedRanges.toolMinor);
222 }
223
224 if (mOrientedRanges.haveOrientation) {
225 info->addMotionRange(mOrientedRanges.orientation);
226 }
227
228 if (mOrientedRanges.haveDistance) {
229 info->addMotionRange(mOrientedRanges.distance);
230 }
231
232 if (mOrientedRanges.haveTilt) {
233 info->addMotionRange(mOrientedRanges.tilt);
234 }
235
236 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
237 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
238 0.0f);
239 }
240 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
241 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
242 0.0f);
243 }
Michael Wright227c5542020-07-02 18:30:52 +0100244 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700245 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
246 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
247 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
248 x.fuzz, x.resolution);
249 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
250 y.fuzz, y.resolution);
251 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
252 x.fuzz, x.resolution);
253 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
254 y.fuzz, y.resolution);
255 }
256 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
257 }
258}
259
260void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700261 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
262 NamedEnum::string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700263 dumpParameters(dump);
264 dumpVirtualKeys(dump);
265 dumpRawPointerAxes(dump);
266 dumpCalibration(dump);
267 dumpAffineTransformation(dump);
268 dumpSurface(dump);
269
270 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
271 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
272 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
273 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
274 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
275 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
276 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
277 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
278 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
279 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
280 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
281 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
282 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
283 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
284 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
285 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
286 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
287
288 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
289 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
290 mLastRawState.rawPointerData.pointerCount);
291 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
292 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
293 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
294 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
295 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
296 "toolType=%d, isHovering=%s\n",
297 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
298 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
299 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
300 pointer.distance, pointer.toolType, toString(pointer.isHovering));
301 }
302
303 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
304 mLastCookedState.buttonState);
305 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
306 mLastCookedState.cookedPointerData.pointerCount);
307 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
308 const PointerProperties& pointerProperties =
309 mLastCookedState.cookedPointerData.pointerProperties[i];
310 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000311 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
312 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
313 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
315 "toolType=%d, isHovering=%s\n",
316 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
327 pointerProperties.toolType,
328 toString(mLastCookedState.cookedPointerData.isHovering(i)));
329 }
330
331 dump += INDENT3 "Stylus Fusion:\n";
332 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
333 toString(mExternalStylusConnected));
334 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
335 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
336 mExternalStylusFusionTimeout);
337 dump += INDENT3 "External Stylus State:\n";
338 dumpStylusState(dump, mExternalStylusState);
339
Michael Wright227c5542020-07-02 18:30:52 +0100340 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
342 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
343 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
344 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
345 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
346 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
347 }
348}
349
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
351 uint32_t changes) {
352 InputMapper::configure(when, config, changes);
353
354 mConfig = *config;
355
356 if (!changes) { // first time only
357 // Configure basic parameters.
358 configureParameters();
359
360 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mCursorScrollAccumulator.configure(getDeviceContext());
362 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700363
364 // Configure absolute axis information.
365 configureRawPointerAxes();
366
367 // Prepare input device calibration.
368 parseCalibration();
369 resolveCalibration();
370 }
371
372 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
373 // Update location calibration to reflect current settings
374 updateAffineTransformation();
375 }
376
377 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
378 // Update pointer speed.
379 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
380 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
381 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 }
383
384 bool resetNeeded = false;
385 if (!changes ||
386 (changes &
387 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800388 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
390 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
391 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
392 // Configure device sources, surface dimensions, orientation and
393 // scaling factors.
394 configureSurface(when, &resetNeeded);
395 }
396
397 if (changes && resetNeeded) {
398 // Send reset, unless this is the first time the device has been configured,
399 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +0000400 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
401 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 }
403}
404
405void TouchInputMapper::resolveExternalStylusPresence() {
406 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800407 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700408 mExternalStylusConnected = !devices.empty();
409
410 if (!mExternalStylusConnected) {
411 resetExternalStylus();
412 }
413}
414
415void TouchInputMapper::configureParameters() {
416 // Use the pointer presentation mode for devices that do not support distinct
417 // multitouch. The spot-based presentation relies on being able to accurately
418 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100420 ? Parameters::GestureMode::SINGLE_TOUCH
421 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422
423 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800424 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
425 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100427 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100429 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700430 } else if (gestureModeString != "default") {
431 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
432 }
433 }
434
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800435 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100437 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800438 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800441 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
442 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 // The device is a cursor device with a touch pad attached.
444 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100445 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446 } else {
447 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100448 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449 }
450
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800451 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452
453 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
455 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100461 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100463 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700464 } else if (deviceTypeString != "default") {
465 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
466 }
467 }
468
Michael Wright227c5542020-07-02 18:30:52 +0100469 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800470 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
471 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472
473 mParameters.hasAssociatedDisplay = false;
474 mParameters.associatedDisplayIsExternal = false;
475 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100476 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
477 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700478 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100479 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800480 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800482 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
483 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
485 }
486 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800487 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488 mParameters.hasAssociatedDisplay = true;
489 }
490
491 // Initial downs on external touch devices should wake the device.
492 // Normally we don't do this for internal touch screens to prevent them from waking
493 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 mParameters.wake = getDeviceContext().isExternal();
495 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496}
497
498void TouchInputMapper::dumpParameters(std::string& dump) {
499 dump += INDENT3 "Parameters:\n";
500
Chris Yea03dd232020-09-08 19:21:09 -0700501 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502
Chris Yea03dd232020-09-08 19:21:09 -0700503 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700504
505 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
506 "displayId='%s'\n",
507 toString(mParameters.hasAssociatedDisplay),
508 toString(mParameters.associatedDisplayIsExternal),
509 mParameters.uniqueDisplayId.c_str());
510 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
511}
512
513void TouchInputMapper::configureRawPointerAxes() {
514 mRawPointerAxes.clear();
515}
516
517void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
518 dump += INDENT3 "Raw Touch Axes:\n";
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
531 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
532}
533
534bool TouchInputMapper::hasExternalStylus() const {
535 return mExternalStylusConnected;
536}
537
538/**
539 * Determine which DisplayViewport to use.
540 * 1. If display port is specified, return the matching viewport. If matching viewport not
541 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800542 * 2. Always use the suggested viewport from WindowManagerService for pointers.
543 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700544 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800545 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700546 */
547std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800548 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800549 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700550 if (displayPort) {
551 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800552 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700553 }
554
Michael Wright227c5542020-07-02 18:30:52 +0100555 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800556 std::optional<DisplayViewport> viewport =
557 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
558 if (viewport) {
559 return viewport;
560 } else {
561 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
562 mConfig.defaultPointerDisplayId);
563 }
564 }
565
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 // Check if uniqueDisplayId is specified in idc file.
567 if (!mParameters.uniqueDisplayId.empty()) {
568 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
569 }
570
571 ViewportType viewportTypeToUse;
572 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100573 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700574 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100575 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700576 }
577
578 std::optional<DisplayViewport> viewport =
579 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100580 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700581 ALOGW("Input device %s should be associated with external display, "
582 "fallback to internal one for the external viewport is not found.",
583 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100584 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700585 }
586
587 return viewport;
588 }
589
590 // No associated display, return a non-display viewport.
591 DisplayViewport newViewport;
592 // Raw width and height in the natural orientation.
593 int32_t rawWidth = mRawPointerAxes.getRawWidth();
594 int32_t rawHeight = mRawPointerAxes.getRawHeight();
595 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
596 return std::make_optional(newViewport);
597}
598
599void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100600 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700601
602 resolveExternalStylusPresence();
603
604 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100605 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800606 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700607 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100608 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700609 if (hasStylus()) {
610 mSource |= AINPUT_SOURCE_STYLUS;
611 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800612 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700613 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100614 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700615 if (hasStylus()) {
616 mSource |= AINPUT_SOURCE_STYLUS;
617 }
618 if (hasExternalStylus()) {
619 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
620 }
Michael Wright227c5542020-07-02 18:30:52 +0100621 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700622 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100623 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700624 } else {
625 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100626 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700627 }
628
629 // Ensure we have valid X and Y axes.
630 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
631 ALOGW("Touch device '%s' did not report support for X or Y axis! "
632 "The device will be inoperable.",
633 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100634 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700635 return;
636 }
637
638 // Get associated display dimensions.
639 std::optional<DisplayViewport> newViewport = findViewport();
640 if (!newViewport) {
641 ALOGI("Touch device '%s' could not query the properties of its associated "
642 "display. The device will be inoperable until the display size "
643 "becomes available.",
644 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100645 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700646 return;
647 }
648
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000649 if (!newViewport->isActive) {
650 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
651 getDeviceName().c_str(), getDeviceId());
652 mDeviceMode = DeviceMode::DISABLED;
653 return;
654 }
655
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700656 // Raw width and height in the natural orientation.
657 int32_t rawWidth = mRawPointerAxes.getRawWidth();
658 int32_t rawHeight = mRawPointerAxes.getRawHeight();
659
660 bool viewportChanged = mViewport != *newViewport;
661 if (viewportChanged) {
662 mViewport = *newViewport;
663
Michael Wright227c5542020-07-02 18:30:52 +0100664 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700665 // Convert rotated viewport to natural surface coordinates.
666 int32_t naturalLogicalWidth, naturalLogicalHeight;
667 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
668 int32_t naturalPhysicalLeft, naturalPhysicalTop;
669 int32_t naturalDeviceWidth, naturalDeviceHeight;
670 switch (mViewport.orientation) {
671 case DISPLAY_ORIENTATION_90:
672 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
673 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
674 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
675 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800676 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700677 naturalPhysicalTop = mViewport.physicalLeft;
678 naturalDeviceWidth = mViewport.deviceHeight;
679 naturalDeviceHeight = mViewport.deviceWidth;
680 break;
681 case DISPLAY_ORIENTATION_180:
682 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
683 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
684 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
685 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
686 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
687 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
688 naturalDeviceWidth = mViewport.deviceWidth;
689 naturalDeviceHeight = mViewport.deviceHeight;
690 break;
691 case DISPLAY_ORIENTATION_270:
692 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
693 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
694 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
695 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
696 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800697 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700698 naturalDeviceWidth = mViewport.deviceHeight;
699 naturalDeviceHeight = mViewport.deviceWidth;
700 break;
701 case DISPLAY_ORIENTATION_0:
702 default:
703 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
704 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
705 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
706 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
707 naturalPhysicalLeft = mViewport.physicalLeft;
708 naturalPhysicalTop = mViewport.physicalTop;
709 naturalDeviceWidth = mViewport.deviceWidth;
710 naturalDeviceHeight = mViewport.deviceHeight;
711 break;
712 }
713
714 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
715 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
716 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
717 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
718 }
719
720 mPhysicalWidth = naturalPhysicalWidth;
721 mPhysicalHeight = naturalPhysicalHeight;
722 mPhysicalLeft = naturalPhysicalLeft;
723 mPhysicalTop = naturalPhysicalTop;
724
Arthur Hung4197f6b2020-03-16 15:39:59 +0800725 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
726 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700727 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
728 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800729 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
730 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700731
732 mSurfaceOrientation =
733 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
734 } else {
735 mPhysicalWidth = rawWidth;
736 mPhysicalHeight = rawHeight;
737 mPhysicalLeft = 0;
738 mPhysicalTop = 0;
739
Arthur Hung4197f6b2020-03-16 15:39:59 +0800740 mRawSurfaceWidth = rawWidth;
741 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700742 mSurfaceLeft = 0;
743 mSurfaceTop = 0;
744 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
745 }
746 }
747
748 // If moving between pointer modes, need to reset some state.
749 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
750 if (deviceModeChanged) {
751 mOrientedRanges.clear();
752 }
753
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800754 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
755 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100756 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800757 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
758 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800759 if (mPointerController == nullptr) {
760 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700761 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800762 if (mConfig.pointerCapture) {
763 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
764 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700765 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100766 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700767 }
768
769 if (viewportChanged || deviceModeChanged) {
770 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
771 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800772 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700773 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
774
775 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800776 mXScale = float(mRawSurfaceWidth) / rawWidth;
777 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700778 mXTranslate = -mSurfaceLeft;
779 mYTranslate = -mSurfaceTop;
780 mXPrecision = 1.0f / mXScale;
781 mYPrecision = 1.0f / mYScale;
782
783 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
784 mOrientedRanges.x.source = mSource;
785 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
786 mOrientedRanges.y.source = mSource;
787
788 configureVirtualKeys();
789
790 // Scale factor for terms that are not oriented in a particular axis.
791 // If the pixels are square then xScale == yScale otherwise we fake it
792 // by choosing an average.
793 mGeometricScale = avg(mXScale, mYScale);
794
795 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800796 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700797
798 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100799 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700800 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
801 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
802 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
803 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
804 } else {
805 mSizeScale = 0.0f;
806 }
807
808 mOrientedRanges.haveTouchSize = true;
809 mOrientedRanges.haveToolSize = true;
810 mOrientedRanges.haveSize = true;
811
812 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
813 mOrientedRanges.touchMajor.source = mSource;
814 mOrientedRanges.touchMajor.min = 0;
815 mOrientedRanges.touchMajor.max = diagonalSize;
816 mOrientedRanges.touchMajor.flat = 0;
817 mOrientedRanges.touchMajor.fuzz = 0;
818 mOrientedRanges.touchMajor.resolution = 0;
819
820 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
821 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
822
823 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
824 mOrientedRanges.toolMajor.source = mSource;
825 mOrientedRanges.toolMajor.min = 0;
826 mOrientedRanges.toolMajor.max = diagonalSize;
827 mOrientedRanges.toolMajor.flat = 0;
828 mOrientedRanges.toolMajor.fuzz = 0;
829 mOrientedRanges.toolMajor.resolution = 0;
830
831 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
832 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
833
834 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
835 mOrientedRanges.size.source = mSource;
836 mOrientedRanges.size.min = 0;
837 mOrientedRanges.size.max = 1.0;
838 mOrientedRanges.size.flat = 0;
839 mOrientedRanges.size.fuzz = 0;
840 mOrientedRanges.size.resolution = 0;
841 } else {
842 mSizeScale = 0.0f;
843 }
844
845 // Pressure factors.
846 mPressureScale = 0;
847 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100848 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
849 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700850 if (mCalibration.havePressureScale) {
851 mPressureScale = mCalibration.pressureScale;
852 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
853 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
854 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
855 }
856 }
857
858 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
859 mOrientedRanges.pressure.source = mSource;
860 mOrientedRanges.pressure.min = 0;
861 mOrientedRanges.pressure.max = pressureMax;
862 mOrientedRanges.pressure.flat = 0;
863 mOrientedRanges.pressure.fuzz = 0;
864 mOrientedRanges.pressure.resolution = 0;
865
866 // Tilt
867 mTiltXCenter = 0;
868 mTiltXScale = 0;
869 mTiltYCenter = 0;
870 mTiltYScale = 0;
871 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
872 if (mHaveTilt) {
873 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
874 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
875 mTiltXScale = M_PI / 180;
876 mTiltYScale = M_PI / 180;
877
878 mOrientedRanges.haveTilt = true;
879
880 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
881 mOrientedRanges.tilt.source = mSource;
882 mOrientedRanges.tilt.min = 0;
883 mOrientedRanges.tilt.max = M_PI_2;
884 mOrientedRanges.tilt.flat = 0;
885 mOrientedRanges.tilt.fuzz = 0;
886 mOrientedRanges.tilt.resolution = 0;
887 }
888
889 // Orientation
890 mOrientationScale = 0;
891 if (mHaveTilt) {
892 mOrientedRanges.haveOrientation = true;
893
894 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
895 mOrientedRanges.orientation.source = mSource;
896 mOrientedRanges.orientation.min = -M_PI;
897 mOrientedRanges.orientation.max = M_PI;
898 mOrientedRanges.orientation.flat = 0;
899 mOrientedRanges.orientation.fuzz = 0;
900 mOrientedRanges.orientation.resolution = 0;
901 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100902 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100904 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700905 if (mRawPointerAxes.orientation.valid) {
906 if (mRawPointerAxes.orientation.maxValue > 0) {
907 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
908 } else if (mRawPointerAxes.orientation.minValue < 0) {
909 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
910 } else {
911 mOrientationScale = 0;
912 }
913 }
914 }
915
916 mOrientedRanges.haveOrientation = true;
917
918 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
919 mOrientedRanges.orientation.source = mSource;
920 mOrientedRanges.orientation.min = -M_PI_2;
921 mOrientedRanges.orientation.max = M_PI_2;
922 mOrientedRanges.orientation.flat = 0;
923 mOrientedRanges.orientation.fuzz = 0;
924 mOrientedRanges.orientation.resolution = 0;
925 }
926
927 // Distance
928 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100929 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
930 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 if (mCalibration.haveDistanceScale) {
932 mDistanceScale = mCalibration.distanceScale;
933 } else {
934 mDistanceScale = 1.0f;
935 }
936 }
937
938 mOrientedRanges.haveDistance = true;
939
940 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
941 mOrientedRanges.distance.source = mSource;
942 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
943 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
944 mOrientedRanges.distance.flat = 0;
945 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
946 mOrientedRanges.distance.resolution = 0;
947 }
948
949 // Compute oriented precision, scales and ranges.
950 // Note that the maximum value reported is an inclusive maximum value so it is one
951 // unit less than the total width or height of surface.
952 switch (mSurfaceOrientation) {
953 case DISPLAY_ORIENTATION_90:
954 case DISPLAY_ORIENTATION_270:
955 mOrientedXPrecision = mYPrecision;
956 mOrientedYPrecision = mXPrecision;
957
958 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800959 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700960 mOrientedRanges.x.flat = 0;
961 mOrientedRanges.x.fuzz = 0;
962 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
963
964 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800965 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966 mOrientedRanges.y.flat = 0;
967 mOrientedRanges.y.fuzz = 0;
968 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
969 break;
970
971 default:
972 mOrientedXPrecision = mXPrecision;
973 mOrientedYPrecision = mYPrecision;
974
975 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800976 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977 mOrientedRanges.x.flat = 0;
978 mOrientedRanges.x.fuzz = 0;
979 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
980
981 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800982 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700983 mOrientedRanges.y.flat = 0;
984 mOrientedRanges.y.fuzz = 0;
985 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
986 break;
987 }
988
989 // Location
990 updateAffineTransformation();
991
Michael Wright227c5542020-07-02 18:30:52 +0100992 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700993 // Compute pointer gesture detection parameters.
994 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +0800995 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996
997 // Scale movements such that one whole swipe of the touch pad covers a
998 // given area relative to the diagonal size of the display when no acceleration
999 // is applied.
1000 // Assume that the touch pad has a square aspect ratio such that movements in
1001 // X and Y of the same number of raw units cover the same physical distance.
1002 mPointerXMovementScale =
1003 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1004 mPointerYMovementScale = mPointerXMovementScale;
1005
1006 // Scale zooms to cover a smaller range of the display than movements do.
1007 // This value determines the area around the pointer that is affected by freeform
1008 // pointer gestures.
1009 mPointerXZoomScale =
1010 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1011 mPointerYZoomScale = mPointerXZoomScale;
1012
1013 // Max width between pointers to detect a swipe gesture is more than some fraction
1014 // of the diagonal axis of the touch pad. Touches that are wider than this are
1015 // translated into freeform gestures.
1016 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1017
1018 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001019 const nsecs_t readTime = when; // synthetic event
1020 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001021 }
1022
1023 // Inform the dispatcher about the changes.
1024 *outResetNeeded = true;
1025 bumpGeneration();
1026 }
1027}
1028
1029void TouchInputMapper::dumpSurface(std::string& dump) {
1030 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001031 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1032 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001033 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1034 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001035 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1036 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001037 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1038 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1039 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1040 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1041 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1042}
1043
1044void TouchInputMapper::configureVirtualKeys() {
1045 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001046 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001047
1048 mVirtualKeys.clear();
1049
1050 if (virtualKeyDefinitions.size() == 0) {
1051 return;
1052 }
1053
1054 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1055 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1056 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1057 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1058
1059 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1060 VirtualKey virtualKey;
1061
1062 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1063 int32_t keyCode;
1064 int32_t dummyKeyMetaState;
1065 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001066 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1067 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001068 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1069 continue; // drop the key
1070 }
1071
1072 virtualKey.keyCode = keyCode;
1073 virtualKey.flags = flags;
1074
1075 // convert the key definition's display coordinates into touch coordinates for a hit box
1076 int32_t halfWidth = virtualKeyDefinition.width / 2;
1077 int32_t halfHeight = virtualKeyDefinition.height / 2;
1078
1079 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001080 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001081 touchScreenLeft;
1082 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001083 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001084 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001085 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1086 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001087 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001088 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1089 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001090 touchScreenTop;
1091 mVirtualKeys.push_back(virtualKey);
1092 }
1093}
1094
1095void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1096 if (!mVirtualKeys.empty()) {
1097 dump += INDENT3 "Virtual Keys:\n";
1098
1099 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1100 const VirtualKey& virtualKey = mVirtualKeys[i];
1101 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1102 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1103 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1104 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1105 }
1106 }
1107}
1108
1109void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001110 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111 Calibration& out = mCalibration;
1112
1113 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001114 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001115 String8 sizeCalibrationString;
1116 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1117 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001118 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001119 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001120 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001121 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001122 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001124 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001125 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001126 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001127 } else if (sizeCalibrationString != "default") {
1128 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1129 }
1130 }
1131
1132 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1133 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1134 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1135
1136 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001137 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138 String8 pressureCalibrationString;
1139 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1140 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001141 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001145 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 } else if (pressureCalibrationString != "default") {
1147 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1148 pressureCalibrationString.string());
1149 }
1150 }
1151
1152 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1153
1154 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001155 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001156 String8 orientationCalibrationString;
1157 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1158 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001159 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001161 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001162 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001164 } else if (orientationCalibrationString != "default") {
1165 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1166 orientationCalibrationString.string());
1167 }
1168 }
1169
1170 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 String8 distanceCalibrationString;
1173 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1174 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 } else if (distanceCalibrationString != "default") {
1179 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1180 distanceCalibrationString.string());
1181 }
1182 }
1183
1184 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1185
Michael Wright227c5542020-07-02 18:30:52 +01001186 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001187 String8 coverageCalibrationString;
1188 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1189 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 } else if (coverageCalibrationString != "default") {
1194 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1195 coverageCalibrationString.string());
1196 }
1197 }
1198}
1199
1200void TouchInputMapper::resolveCalibration() {
1201 // Size
1202 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001203 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1204 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 }
1206 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001207 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 }
1209
1210 // Pressure
1211 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001212 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1213 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 }
1215 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001216 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 }
1218
1219 // Orientation
1220 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001221 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1222 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 }
1224 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001225 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226 }
1227
1228 // Distance
1229 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001230 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1231 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 }
1233 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001234 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235 }
1236
1237 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001238 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1239 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 }
1241}
1242
1243void TouchInputMapper::dumpCalibration(std::string& dump) {
1244 dump += INDENT3 "Calibration:\n";
1245
1246 // Size
1247 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001248 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 dump += INDENT4 "touch.size.calibration: none\n";
1250 break;
Michael Wright227c5542020-07-02 18:30:52 +01001251 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 dump += INDENT4 "touch.size.calibration: geometric\n";
1253 break;
Michael Wright227c5542020-07-02 18:30:52 +01001254 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 dump += INDENT4 "touch.size.calibration: diameter\n";
1256 break;
Michael Wright227c5542020-07-02 18:30:52 +01001257 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 dump += INDENT4 "touch.size.calibration: box\n";
1259 break;
Michael Wright227c5542020-07-02 18:30:52 +01001260 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 dump += INDENT4 "touch.size.calibration: area\n";
1262 break;
1263 default:
1264 ALOG_ASSERT(false);
1265 }
1266
1267 if (mCalibration.haveSizeScale) {
1268 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1269 }
1270
1271 if (mCalibration.haveSizeBias) {
1272 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1273 }
1274
1275 if (mCalibration.haveSizeIsSummed) {
1276 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1277 toString(mCalibration.sizeIsSummed));
1278 }
1279
1280 // Pressure
1281 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001282 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 dump += INDENT4 "touch.pressure.calibration: none\n";
1284 break;
Michael Wright227c5542020-07-02 18:30:52 +01001285 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286 dump += INDENT4 "touch.pressure.calibration: physical\n";
1287 break;
Michael Wright227c5542020-07-02 18:30:52 +01001288 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1290 break;
1291 default:
1292 ALOG_ASSERT(false);
1293 }
1294
1295 if (mCalibration.havePressureScale) {
1296 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1297 }
1298
1299 // Orientation
1300 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001301 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001302 dump += INDENT4 "touch.orientation.calibration: none\n";
1303 break;
Michael Wright227c5542020-07-02 18:30:52 +01001304 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1306 break;
Michael Wright227c5542020-07-02 18:30:52 +01001307 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 dump += INDENT4 "touch.orientation.calibration: vector\n";
1309 break;
1310 default:
1311 ALOG_ASSERT(false);
1312 }
1313
1314 // Distance
1315 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001316 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 dump += INDENT4 "touch.distance.calibration: none\n";
1318 break;
Michael Wright227c5542020-07-02 18:30:52 +01001319 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 dump += INDENT4 "touch.distance.calibration: scaled\n";
1321 break;
1322 default:
1323 ALOG_ASSERT(false);
1324 }
1325
1326 if (mCalibration.haveDistanceScale) {
1327 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1328 }
1329
1330 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.coverage.calibration: none\n";
1333 break;
Michael Wright227c5542020-07-02 18:30:52 +01001334 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001335 dump += INDENT4 "touch.coverage.calibration: box\n";
1336 break;
1337 default:
1338 ALOG_ASSERT(false);
1339 }
1340}
1341
1342void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1343 dump += INDENT3 "Affine Transformation:\n";
1344
1345 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1346 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1347 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1348 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1349 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1350 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1351}
1352
1353void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001354 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001355 mSurfaceOrientation);
1356}
1357
1358void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001359 mCursorButtonAccumulator.reset(getDeviceContext());
1360 mCursorScrollAccumulator.reset(getDeviceContext());
1361 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001362
1363 mPointerVelocityControl.reset();
1364 mWheelXVelocityControl.reset();
1365 mWheelYVelocityControl.reset();
1366
1367 mRawStatesPending.clear();
1368 mCurrentRawState.clear();
1369 mCurrentCookedState.clear();
1370 mLastRawState.clear();
1371 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001372 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001373 mSentHoverEnter = false;
1374 mHavePointerIds = false;
1375 mCurrentMotionAborted = false;
1376 mDownTime = 0;
1377
1378 mCurrentVirtualKey.down = false;
1379
1380 mPointerGesture.reset();
1381 mPointerSimple.reset();
1382 resetExternalStylus();
1383
1384 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001385 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386 mPointerController->clearSpots();
1387 }
1388
1389 InputMapper::reset(when);
1390}
1391
1392void TouchInputMapper::resetExternalStylus() {
1393 mExternalStylusState.clear();
1394 mExternalStylusId = -1;
1395 mExternalStylusFusionTimeout = LLONG_MAX;
1396 mExternalStylusDataPending = false;
1397}
1398
1399void TouchInputMapper::clearStylusDataPendingFlags() {
1400 mExternalStylusDataPending = false;
1401 mExternalStylusFusionTimeout = LLONG_MAX;
1402}
1403
1404void TouchInputMapper::process(const RawEvent* rawEvent) {
1405 mCursorButtonAccumulator.process(rawEvent);
1406 mCursorScrollAccumulator.process(rawEvent);
1407 mTouchButtonAccumulator.process(rawEvent);
1408
1409 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001410 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411 }
1412}
1413
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001414void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001415 // Push a new state.
1416 mRawStatesPending.emplace_back();
1417
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001418 RawState& next = mRawStatesPending.back();
1419 next.clear();
1420 next.when = when;
1421 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422
1423 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001424 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001425 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1426
1427 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001428 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1429 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001430 mCursorScrollAccumulator.finishSync();
1431
1432 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001433 syncTouch(when, &next);
1434
1435 // The last RawState is the actually second to last, since we just added a new state
1436 const RawState& last =
1437 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438
1439 // Assign pointer ids.
1440 if (!mHavePointerIds) {
1441 assignPointerIds(last, next);
1442 }
1443
1444#if DEBUG_RAW_EVENTS
1445 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001446 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001447 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1448 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1449 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1450 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451#endif
1452
1453 processRawTouches(false /*timeout*/);
1454}
1455
1456void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001457 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001458 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001459 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001460 mCurrentCookedState.clear();
1461 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001462 return;
1463 }
1464
1465 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1466 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1467 // touching the current state will only observe the events that have been dispatched to the
1468 // rest of the pipeline.
1469 const size_t N = mRawStatesPending.size();
1470 size_t count;
1471 for (count = 0; count < N; count++) {
1472 const RawState& next = mRawStatesPending[count];
1473
1474 // A failure to assign the stylus id means that we're waiting on stylus data
1475 // and so should defer the rest of the pipeline.
1476 if (assignExternalStylusId(next, timeout)) {
1477 break;
1478 }
1479
1480 // All ready to go.
1481 clearStylusDataPendingFlags();
1482 mCurrentRawState.copyFrom(next);
1483 if (mCurrentRawState.when < mLastRawState.when) {
1484 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001485 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001486 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001487 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001488 }
1489 if (count != 0) {
1490 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1491 }
1492
1493 if (mExternalStylusDataPending) {
1494 if (timeout) {
1495 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1496 clearStylusDataPendingFlags();
1497 mCurrentRawState.copyFrom(mLastRawState);
1498#if DEBUG_STYLUS_FUSION
1499 ALOGD("Timeout expired, synthesizing event with new stylus data");
1500#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001501 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1502 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001503 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1504 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1505 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1506 }
1507 }
1508}
1509
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001510void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001511 // Always start with a clean state.
1512 mCurrentCookedState.clear();
1513
1514 // Apply stylus buttons to current raw state.
1515 applyExternalStylusButtonState(when);
1516
1517 // Handle policy on initial down or hover events.
1518 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1519 mCurrentRawState.rawPointerData.pointerCount != 0;
1520
1521 uint32_t policyFlags = 0;
1522 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1523 if (initialDown || buttonsPressed) {
1524 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001525 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001526 getContext()->fadePointer();
1527 }
1528
1529 if (mParameters.wake) {
1530 policyFlags |= POLICY_FLAG_WAKE;
1531 }
1532 }
1533
1534 // Consume raw off-screen touches before cooking pointer data.
1535 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001536 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001537 mCurrentRawState.rawPointerData.clear();
1538 }
1539
1540 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1541 // with cooked pointer data that has the same ids and indices as the raw data.
1542 // The following code can use either the raw or cooked data, as needed.
1543 cookPointerData();
1544
1545 // Apply stylus pressure to current cooked state.
1546 applyExternalStylusTouchState(when);
1547
1548 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001549 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1550 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001551 mCurrentCookedState.buttonState);
1552
1553 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001554 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001555 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1556 uint32_t id = idBits.clearFirstMarkedBit();
1557 const RawPointerData::Pointer& pointer =
1558 mCurrentRawState.rawPointerData.pointerForId(id);
1559 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1560 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1561 mCurrentCookedState.stylusIdBits.markBit(id);
1562 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1563 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1564 mCurrentCookedState.fingerIdBits.markBit(id);
1565 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1566 mCurrentCookedState.mouseIdBits.markBit(id);
1567 }
1568 }
1569 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1570 uint32_t id = idBits.clearFirstMarkedBit();
1571 const RawPointerData::Pointer& pointer =
1572 mCurrentRawState.rawPointerData.pointerForId(id);
1573 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1574 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1575 mCurrentCookedState.stylusIdBits.markBit(id);
1576 }
1577 }
1578
1579 // Stylus takes precedence over all tools, then mouse, then finger.
1580 PointerUsage pointerUsage = mPointerUsage;
1581 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1582 mCurrentCookedState.mouseIdBits.clear();
1583 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001584 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001585 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1586 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001587 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001588 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1589 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001590 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 }
1592
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001593 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001594 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001595 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596
1597 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001598 dispatchButtonRelease(when, readTime, policyFlags);
1599 dispatchHoverExit(when, readTime, policyFlags);
1600 dispatchTouches(when, readTime, policyFlags);
1601 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1602 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001603 }
1604
1605 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1606 mCurrentMotionAborted = false;
1607 }
1608 }
1609
1610 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001611 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001612 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1613 mCurrentCookedState.buttonState);
1614
1615 // Clear some transient state.
1616 mCurrentRawState.rawVScroll = 0;
1617 mCurrentRawState.rawHScroll = 0;
1618
1619 // Copy current touch to last touch in preparation for the next cycle.
1620 mLastRawState.copyFrom(mCurrentRawState);
1621 mLastCookedState.copyFrom(mCurrentCookedState);
1622}
1623
Garfield Tanc734e4f2021-01-15 20:01:39 -08001624void TouchInputMapper::updateTouchSpots() {
1625 if (!mConfig.showTouches || mPointerController == nullptr) {
1626 return;
1627 }
1628
1629 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1630 // clear touch spots.
1631 if (mDeviceMode != DeviceMode::DIRECT &&
1632 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1633 return;
1634 }
1635
1636 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1637 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1638
1639 mPointerController->setButtonState(mCurrentRawState.buttonState);
1640 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1641 mCurrentCookedState.cookedPointerData.idToIndex,
1642 mCurrentCookedState.cookedPointerData.touchingIdBits,
1643 mViewport.displayId);
1644}
1645
1646bool TouchInputMapper::isTouchScreen() {
1647 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1648 mParameters.hasAssociatedDisplay;
1649}
1650
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001651void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001652 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001653 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1654 }
1655}
1656
1657void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1658 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1659 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1660
1661 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1662 float pressure = mExternalStylusState.pressure;
1663 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1664 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1665 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1666 }
1667 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1668 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1669
1670 PointerProperties& properties =
1671 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1672 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1673 properties.toolType = mExternalStylusState.toolType;
1674 }
1675 }
1676}
1677
1678bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001679 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001680 return false;
1681 }
1682
1683 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1684 state.rawPointerData.pointerCount != 0;
1685 if (initialDown) {
1686 if (mExternalStylusState.pressure != 0.0f) {
1687#if DEBUG_STYLUS_FUSION
1688 ALOGD("Have both stylus and touch data, beginning fusion");
1689#endif
1690 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1691 } else if (timeout) {
1692#if DEBUG_STYLUS_FUSION
1693 ALOGD("Timeout expired, assuming touch is not a stylus.");
1694#endif
1695 resetExternalStylus();
1696 } else {
1697 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1698 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1699 }
1700#if DEBUG_STYLUS_FUSION
1701 ALOGD("No stylus data but stylus is connected, requesting timeout "
1702 "(%" PRId64 "ms)",
1703 mExternalStylusFusionTimeout);
1704#endif
1705 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1706 return true;
1707 }
1708 }
1709
1710 // Check if the stylus pointer has gone up.
1711 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1712#if DEBUG_STYLUS_FUSION
1713 ALOGD("Stylus pointer is going up");
1714#endif
1715 mExternalStylusId = -1;
1716 }
1717
1718 return false;
1719}
1720
1721void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001722 if (mDeviceMode == DeviceMode::POINTER) {
1723 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001724 // Since this is a synthetic event, we can consider its latency to be zero
1725 const nsecs_t readTime = when;
1726 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001727 }
Michael Wright227c5542020-07-02 18:30:52 +01001728 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001729 if (mExternalStylusFusionTimeout < when) {
1730 processRawTouches(true /*timeout*/);
1731 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1732 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1733 }
1734 }
1735}
1736
1737void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1738 mExternalStylusState.copyFrom(state);
1739 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1740 // We're either in the middle of a fused stream of data or we're waiting on data before
1741 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1742 // data.
1743 mExternalStylusDataPending = true;
1744 processRawTouches(false /*timeout*/);
1745 }
1746}
1747
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001748bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001749 // Check for release of a virtual key.
1750 if (mCurrentVirtualKey.down) {
1751 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1752 // Pointer went up while virtual key was down.
1753 mCurrentVirtualKey.down = false;
1754 if (!mCurrentVirtualKey.ignored) {
1755#if DEBUG_VIRTUAL_KEYS
1756 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1757 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1758#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001759 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001760 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1761 }
1762 return true;
1763 }
1764
1765 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1766 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1767 const RawPointerData::Pointer& pointer =
1768 mCurrentRawState.rawPointerData.pointerForId(id);
1769 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1770 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1771 // Pointer is still within the space of the virtual key.
1772 return true;
1773 }
1774 }
1775
1776 // Pointer left virtual key area or another pointer also went down.
1777 // Send key cancellation but do not consume the touch yet.
1778 // This is useful when the user swipes through from the virtual key area
1779 // into the main display surface.
1780 mCurrentVirtualKey.down = false;
1781 if (!mCurrentVirtualKey.ignored) {
1782#if DEBUG_VIRTUAL_KEYS
1783 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1784 mCurrentVirtualKey.scanCode);
1785#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001786 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001787 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1788 AKEY_EVENT_FLAG_CANCELED);
1789 }
1790 }
1791
1792 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1793 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1794 // Pointer just went down. Check for virtual key press or off-screen touches.
1795 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1796 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001797 // Exclude unscaled device for inside surface checking.
1798 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001799 // If exactly one pointer went down, check for virtual key hit.
1800 // Otherwise we will drop the entire stroke.
1801 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1802 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1803 if (virtualKey) {
1804 mCurrentVirtualKey.down = true;
1805 mCurrentVirtualKey.downTime = when;
1806 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1807 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1808 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001809 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1810 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001811
1812 if (!mCurrentVirtualKey.ignored) {
1813#if DEBUG_VIRTUAL_KEYS
1814 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1815 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1816#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001817 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001818 AKEY_EVENT_FLAG_FROM_SYSTEM |
1819 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1820 }
1821 }
1822 }
1823 return true;
1824 }
1825 }
1826
1827 // Disable all virtual key touches that happen within a short time interval of the
1828 // most recent touch within the screen area. The idea is to filter out stray
1829 // virtual key presses when interacting with the touch screen.
1830 //
1831 // Problems we're trying to solve:
1832 //
1833 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1834 // virtual key area that is implemented by a separate touch panel and accidentally
1835 // triggers a virtual key.
1836 //
1837 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1838 // area and accidentally triggers a virtual key. This often happens when virtual keys
1839 // are layed out below the screen near to where the on screen keyboard's space bar
1840 // is displayed.
1841 if (mConfig.virtualKeyQuietTime > 0 &&
1842 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001843 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001844 }
1845 return false;
1846}
1847
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001848void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001849 int32_t keyEventAction, int32_t keyEventFlags) {
1850 int32_t keyCode = mCurrentVirtualKey.keyCode;
1851 int32_t scanCode = mCurrentVirtualKey.scanCode;
1852 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001853 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854 policyFlags |= POLICY_FLAG_VIRTUAL;
1855
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001856 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1857 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1858 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001859 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001860}
1861
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001862void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001863 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1864 if (!currentIdBits.isEmpty()) {
1865 int32_t metaState = getContext()->getGlobalMetaState();
1866 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001867 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1868 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001869 mCurrentCookedState.cookedPointerData.pointerProperties,
1870 mCurrentCookedState.cookedPointerData.pointerCoords,
1871 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1872 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1873 mCurrentMotionAborted = true;
1874 }
1875}
1876
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001877void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001878 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1879 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1880 int32_t metaState = getContext()->getGlobalMetaState();
1881 int32_t buttonState = mCurrentCookedState.buttonState;
1882
1883 if (currentIdBits == lastIdBits) {
1884 if (!currentIdBits.isEmpty()) {
1885 // No pointer id changes so this is a move event.
1886 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001887 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1888 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001889 mCurrentCookedState.cookedPointerData.pointerProperties,
1890 mCurrentCookedState.cookedPointerData.pointerCoords,
1891 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1892 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1893 }
1894 } else {
1895 // There may be pointers going up and pointers going down and pointers moving
1896 // all at the same time.
1897 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1898 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1899 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1900 BitSet32 dispatchedIdBits(lastIdBits.value);
1901
1902 // Update last coordinates of pointers that have moved so that we observe the new
1903 // pointer positions at the same time as other pointers that have just gone up.
1904 bool moveNeeded =
1905 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1906 mCurrentCookedState.cookedPointerData.pointerCoords,
1907 mCurrentCookedState.cookedPointerData.idToIndex,
1908 mLastCookedState.cookedPointerData.pointerProperties,
1909 mLastCookedState.cookedPointerData.pointerCoords,
1910 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1911 if (buttonState != mLastCookedState.buttonState) {
1912 moveNeeded = true;
1913 }
1914
1915 // Dispatch pointer up events.
1916 while (!upIdBits.isEmpty()) {
1917 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001918 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001919 if (isCanceled) {
1920 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1921 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001922 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001923 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924 mLastCookedState.cookedPointerData.pointerProperties,
1925 mLastCookedState.cookedPointerData.pointerCoords,
1926 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1927 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1928 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001929 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001930 }
1931
1932 // Dispatch move events if any of the remaining pointers moved from their old locations.
1933 // Although applications receive new locations as part of individual pointer up
1934 // events, they do not generally handle them except when presented in a move event.
1935 if (moveNeeded && !moveIdBits.isEmpty()) {
1936 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001937 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1938 metaState, buttonState, 0,
1939 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001940 mCurrentCookedState.cookedPointerData.pointerCoords,
1941 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1942 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1943 }
1944
1945 // Dispatch pointer down events using the new pointer locations.
1946 while (!downIdBits.isEmpty()) {
1947 uint32_t downId = downIdBits.clearFirstMarkedBit();
1948 dispatchedIdBits.markBit(downId);
1949
1950 if (dispatchedIdBits.count() == 1) {
1951 // First pointer is going down. Set down time.
1952 mDownTime = when;
1953 }
1954
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001955 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
1956 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001957 mCurrentCookedState.cookedPointerData.pointerProperties,
1958 mCurrentCookedState.cookedPointerData.pointerCoords,
1959 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1960 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1961 }
1962 }
1963}
1964
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001965void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001966 if (mSentHoverEnter &&
1967 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1968 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1969 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001970 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
1971 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001972 mLastCookedState.cookedPointerData.pointerProperties,
1973 mLastCookedState.cookedPointerData.pointerCoords,
1974 mLastCookedState.cookedPointerData.idToIndex,
1975 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1976 mOrientedYPrecision, mDownTime);
1977 mSentHoverEnter = false;
1978 }
1979}
1980
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001981void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
1982 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001983 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1984 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1985 int32_t metaState = getContext()->getGlobalMetaState();
1986 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001987 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
1988 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001989 mCurrentCookedState.cookedPointerData.pointerProperties,
1990 mCurrentCookedState.cookedPointerData.pointerCoords,
1991 mCurrentCookedState.cookedPointerData.idToIndex,
1992 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1993 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1994 mSentHoverEnter = true;
1995 }
1996
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001997 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
1998 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001999 mCurrentCookedState.cookedPointerData.pointerProperties,
2000 mCurrentCookedState.cookedPointerData.pointerCoords,
2001 mCurrentCookedState.cookedPointerData.idToIndex,
2002 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2003 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2004 }
2005}
2006
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002007void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002008 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2009 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2010 const int32_t metaState = getContext()->getGlobalMetaState();
2011 int32_t buttonState = mLastCookedState.buttonState;
2012 while (!releasedButtons.isEmpty()) {
2013 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2014 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002015 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002016 actionButton, 0, metaState, buttonState, 0,
2017 mCurrentCookedState.cookedPointerData.pointerProperties,
2018 mCurrentCookedState.cookedPointerData.pointerCoords,
2019 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2020 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2021 }
2022}
2023
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002024void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002025 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2026 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2027 const int32_t metaState = getContext()->getGlobalMetaState();
2028 int32_t buttonState = mLastCookedState.buttonState;
2029 while (!pressedButtons.isEmpty()) {
2030 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2031 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002032 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2033 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002034 mCurrentCookedState.cookedPointerData.pointerProperties,
2035 mCurrentCookedState.cookedPointerData.pointerCoords,
2036 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2037 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2038 }
2039}
2040
2041const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2042 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2043 return cookedPointerData.touchingIdBits;
2044 }
2045 return cookedPointerData.hoveringIdBits;
2046}
2047
2048void TouchInputMapper::cookPointerData() {
2049 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2050
2051 mCurrentCookedState.cookedPointerData.clear();
2052 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2053 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2054 mCurrentRawState.rawPointerData.hoveringIdBits;
2055 mCurrentCookedState.cookedPointerData.touchingIdBits =
2056 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002057 mCurrentCookedState.cookedPointerData.canceledIdBits =
2058 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002059
2060 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2061 mCurrentCookedState.buttonState = 0;
2062 } else {
2063 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2064 }
2065
2066 // Walk through the the active pointers and map device coordinates onto
2067 // surface coordinates and adjust for display orientation.
2068 for (uint32_t i = 0; i < currentPointerCount; i++) {
2069 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2070
2071 // Size
2072 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2073 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002074 case Calibration::SizeCalibration::GEOMETRIC:
2075 case Calibration::SizeCalibration::DIAMETER:
2076 case Calibration::SizeCalibration::BOX:
2077 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002078 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2079 touchMajor = in.touchMajor;
2080 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2081 toolMajor = in.toolMajor;
2082 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2083 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2084 : in.touchMajor;
2085 } else if (mRawPointerAxes.touchMajor.valid) {
2086 toolMajor = touchMajor = in.touchMajor;
2087 toolMinor = touchMinor =
2088 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2089 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2090 : in.touchMajor;
2091 } else if (mRawPointerAxes.toolMajor.valid) {
2092 touchMajor = toolMajor = in.toolMajor;
2093 touchMinor = toolMinor =
2094 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2095 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2096 : in.toolMajor;
2097 } else {
2098 ALOG_ASSERT(false,
2099 "No touch or tool axes. "
2100 "Size calibration should have been resolved to NONE.");
2101 touchMajor = 0;
2102 touchMinor = 0;
2103 toolMajor = 0;
2104 toolMinor = 0;
2105 size = 0;
2106 }
2107
2108 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2109 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2110 if (touchingCount > 1) {
2111 touchMajor /= touchingCount;
2112 touchMinor /= touchingCount;
2113 toolMajor /= touchingCount;
2114 toolMinor /= touchingCount;
2115 size /= touchingCount;
2116 }
2117 }
2118
Michael Wright227c5542020-07-02 18:30:52 +01002119 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002120 touchMajor *= mGeometricScale;
2121 touchMinor *= mGeometricScale;
2122 toolMajor *= mGeometricScale;
2123 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002124 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002125 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2126 touchMinor = touchMajor;
2127 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2128 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002129 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002130 touchMinor = touchMajor;
2131 toolMinor = toolMajor;
2132 }
2133
2134 mCalibration.applySizeScaleAndBias(&touchMajor);
2135 mCalibration.applySizeScaleAndBias(&touchMinor);
2136 mCalibration.applySizeScaleAndBias(&toolMajor);
2137 mCalibration.applySizeScaleAndBias(&toolMinor);
2138 size *= mSizeScale;
2139 break;
2140 default:
2141 touchMajor = 0;
2142 touchMinor = 0;
2143 toolMajor = 0;
2144 toolMinor = 0;
2145 size = 0;
2146 break;
2147 }
2148
2149 // Pressure
2150 float pressure;
2151 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002152 case Calibration::PressureCalibration::PHYSICAL:
2153 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154 pressure = in.pressure * mPressureScale;
2155 break;
2156 default:
2157 pressure = in.isHovering ? 0 : 1;
2158 break;
2159 }
2160
2161 // Tilt and Orientation
2162 float tilt;
2163 float orientation;
2164 if (mHaveTilt) {
2165 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2166 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2167 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2168 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2169 } else {
2170 tilt = 0;
2171
2172 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002173 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002174 orientation = in.orientation * mOrientationScale;
2175 break;
Michael Wright227c5542020-07-02 18:30:52 +01002176 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002177 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2178 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2179 if (c1 != 0 || c2 != 0) {
2180 orientation = atan2f(c1, c2) * 0.5f;
2181 float confidence = hypotf(c1, c2);
2182 float scale = 1.0f + confidence / 16.0f;
2183 touchMajor *= scale;
2184 touchMinor /= scale;
2185 toolMajor *= scale;
2186 toolMinor /= scale;
2187 } else {
2188 orientation = 0;
2189 }
2190 break;
2191 }
2192 default:
2193 orientation = 0;
2194 }
2195 }
2196
2197 // Distance
2198 float distance;
2199 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002200 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002201 distance = in.distance * mDistanceScale;
2202 break;
2203 default:
2204 distance = 0;
2205 }
2206
2207 // Coverage
2208 int32_t rawLeft, rawTop, rawRight, rawBottom;
2209 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002210 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002211 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2212 rawRight = in.toolMinor & 0x0000ffff;
2213 rawBottom = in.toolMajor & 0x0000ffff;
2214 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2215 break;
2216 default:
2217 rawLeft = rawTop = rawRight = rawBottom = 0;
2218 break;
2219 }
2220
2221 // Adjust X,Y coords for device calibration
2222 // TODO: Adjust coverage coords?
2223 float xTransformed = in.x, yTransformed = in.y;
2224 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002225 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002226
2227 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002228 float left, top, right, bottom;
2229
2230 switch (mSurfaceOrientation) {
2231 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002232 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2233 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2234 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2235 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2236 orientation -= M_PI_2;
2237 if (mOrientedRanges.haveOrientation &&
2238 orientation < mOrientedRanges.orientation.min) {
2239 orientation +=
2240 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2241 }
2242 break;
2243 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2245 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2246 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2247 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2248 orientation -= M_PI;
2249 if (mOrientedRanges.haveOrientation &&
2250 orientation < mOrientedRanges.orientation.min) {
2251 orientation +=
2252 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2253 }
2254 break;
2255 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2257 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2258 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2259 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2260 orientation += M_PI_2;
2261 if (mOrientedRanges.haveOrientation &&
2262 orientation > mOrientedRanges.orientation.max) {
2263 orientation -=
2264 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2265 }
2266 break;
2267 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002268 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2269 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2270 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2271 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2272 break;
2273 }
2274
2275 // Write output coords.
2276 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2277 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002278 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2279 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002280 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2281 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2282 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2283 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2284 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2285 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2286 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002287 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002288 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2289 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2290 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2291 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2292 } else {
2293 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2294 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2295 }
2296
Chris Ye364fdb52020-08-05 15:07:56 -07002297 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002298 uint32_t id = in.id;
2299 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2300 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2301 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2302 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2303 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2304 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2305 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2306 }
2307
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002308 // Write output properties.
2309 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002310 properties.clear();
2311 properties.id = id;
2312 properties.toolType = in.toolType;
2313
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002314 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002316 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317 }
2318}
2319
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002320void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002321 PointerUsage pointerUsage) {
2322 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002323 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002324 mPointerUsage = pointerUsage;
2325 }
2326
2327 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002328 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002329 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002330 break;
Michael Wright227c5542020-07-02 18:30:52 +01002331 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002332 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002333 break;
Michael Wright227c5542020-07-02 18:30:52 +01002334 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002335 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002336 break;
Michael Wright227c5542020-07-02 18:30:52 +01002337 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002338 break;
2339 }
2340}
2341
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002342void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002344 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002345 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002346 break;
Michael Wright227c5542020-07-02 18:30:52 +01002347 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002348 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 break;
Michael Wright227c5542020-07-02 18:30:52 +01002350 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002351 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 break;
Michael Wright227c5542020-07-02 18:30:52 +01002353 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 break;
2355 }
2356
Michael Wright227c5542020-07-02 18:30:52 +01002357 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358}
2359
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002360void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2361 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 // Update current gesture coordinates.
2363 bool cancelPreviousGesture, finishPreviousGesture;
2364 bool sendEvents =
2365 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2366 if (!sendEvents) {
2367 return;
2368 }
2369 if (finishPreviousGesture) {
2370 cancelPreviousGesture = false;
2371 }
2372
2373 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002374 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002375 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002376 if (finishPreviousGesture || cancelPreviousGesture) {
2377 mPointerController->clearSpots();
2378 }
2379
Michael Wright227c5542020-07-02 18:30:52 +01002380 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2382 mPointerGesture.currentGestureIdToIndex,
2383 mPointerGesture.currentGestureIdBits,
2384 mPointerController->getDisplayId());
2385 }
2386 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002387 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 }
2389
2390 // Show or hide the pointer if needed.
2391 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002392 case PointerGesture::Mode::NEUTRAL:
2393 case PointerGesture::Mode::QUIET:
2394 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2395 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002397 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 }
2399 break;
Michael Wright227c5542020-07-02 18:30:52 +01002400 case PointerGesture::Mode::TAP:
2401 case PointerGesture::Mode::TAP_DRAG:
2402 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2403 case PointerGesture::Mode::HOVER:
2404 case PointerGesture::Mode::PRESS:
2405 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 // Unfade the pointer when the current gesture manipulates the
2407 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002408 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 break;
Michael Wright227c5542020-07-02 18:30:52 +01002410 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 // Fade the pointer when the current gesture manipulates a different
2412 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002413 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002414 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002416 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 }
2418 break;
2419 }
2420
2421 // Send events!
2422 int32_t metaState = getContext()->getGlobalMetaState();
2423 int32_t buttonState = mCurrentCookedState.buttonState;
2424
2425 // Update last coordinates of pointers that have moved so that we observe the new
2426 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002427 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2428 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2429 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2430 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2431 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2432 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002433 bool moveNeeded = false;
2434 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2435 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2436 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2437 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2438 mPointerGesture.lastGestureIdBits.value);
2439 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2440 mPointerGesture.currentGestureCoords,
2441 mPointerGesture.currentGestureIdToIndex,
2442 mPointerGesture.lastGestureProperties,
2443 mPointerGesture.lastGestureCoords,
2444 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2445 if (buttonState != mLastCookedState.buttonState) {
2446 moveNeeded = true;
2447 }
2448 }
2449
2450 // Send motion events for all pointers that went up or were canceled.
2451 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2452 if (!dispatchedGestureIdBits.isEmpty()) {
2453 if (cancelPreviousGesture) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002454 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2455 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2457 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2458 mPointerGesture.downTime);
2459
2460 dispatchedGestureIdBits.clear();
2461 } else {
2462 BitSet32 upGestureIdBits;
2463 if (finishPreviousGesture) {
2464 upGestureIdBits = dispatchedGestureIdBits;
2465 } else {
2466 upGestureIdBits.value =
2467 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2468 }
2469 while (!upGestureIdBits.isEmpty()) {
2470 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2471
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002472 dispatchMotion(when, readTime, policyFlags, mSource,
2473 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState,
2474 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 mPointerGesture.lastGestureCoords,
2476 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2477 0, mPointerGesture.downTime);
2478
2479 dispatchedGestureIdBits.clearBit(id);
2480 }
2481 }
2482 }
2483
2484 // Send motion events for all pointers that moved.
2485 if (moveNeeded) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002486 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
2487 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002488 mPointerGesture.currentGestureProperties,
2489 mPointerGesture.currentGestureCoords,
2490 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2491 mPointerGesture.downTime);
2492 }
2493
2494 // Send motion events for all pointers that went down.
2495 if (down) {
2496 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2497 ~dispatchedGestureIdBits.value);
2498 while (!downGestureIdBits.isEmpty()) {
2499 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2500 dispatchedGestureIdBits.markBit(id);
2501
2502 if (dispatchedGestureIdBits.count() == 1) {
2503 mPointerGesture.downTime = when;
2504 }
2505
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002506 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2507 0, 0, metaState, buttonState, 0,
2508 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 mPointerGesture.currentGestureCoords,
2510 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2511 0, mPointerGesture.downTime);
2512 }
2513 }
2514
2515 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002516 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002517 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2518 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002519 mPointerGesture.currentGestureProperties,
2520 mPointerGesture.currentGestureCoords,
2521 mPointerGesture.currentGestureIdToIndex,
2522 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2523 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2524 // Synthesize a hover move event after all pointers go up to indicate that
2525 // the pointer is hovering again even if the user is not currently touching
2526 // the touch pad. This ensures that a view will receive a fresh hover enter
2527 // event after a tap.
2528 float x, y;
2529 mPointerController->getPosition(&x, &y);
2530
2531 PointerProperties pointerProperties;
2532 pointerProperties.clear();
2533 pointerProperties.id = 0;
2534 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2535
2536 PointerCoords pointerCoords;
2537 pointerCoords.clear();
2538 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2539 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2540
2541 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002542 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
2543 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2544 metaState, buttonState, MotionClassification::NONE,
2545 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2546 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002547 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002548 }
2549
2550 // Update state.
2551 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2552 if (!down) {
2553 mPointerGesture.lastGestureIdBits.clear();
2554 } else {
2555 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2556 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2557 uint32_t id = idBits.clearFirstMarkedBit();
2558 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2559 mPointerGesture.lastGestureProperties[index].copyFrom(
2560 mPointerGesture.currentGestureProperties[index]);
2561 mPointerGesture.lastGestureCoords[index].copyFrom(
2562 mPointerGesture.currentGestureCoords[index]);
2563 mPointerGesture.lastGestureIdToIndex[id] = index;
2564 }
2565 }
2566}
2567
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002568void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002569 // Cancel previously dispatches pointers.
2570 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2571 int32_t metaState = getContext()->getGlobalMetaState();
2572 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002573 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2574 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002575 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2576 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2577 0, 0, mPointerGesture.downTime);
2578 }
2579
2580 // Reset the current pointer gesture.
2581 mPointerGesture.reset();
2582 mPointerVelocityControl.reset();
2583
2584 // Remove any current spots.
2585 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002586 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002587 mPointerController->clearSpots();
2588 }
2589}
2590
2591bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2592 bool* outFinishPreviousGesture, bool isTimeout) {
2593 *outCancelPreviousGesture = false;
2594 *outFinishPreviousGesture = false;
2595
2596 // Handle TAP timeout.
2597 if (isTimeout) {
2598#if DEBUG_GESTURES
2599 ALOGD("Gestures: Processing timeout");
2600#endif
2601
Michael Wright227c5542020-07-02 18:30:52 +01002602 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002603 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2604 // The tap/drag timeout has not yet expired.
2605 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2606 mConfig.pointerGestureTapDragInterval);
2607 } else {
2608 // The tap is finished.
2609#if DEBUG_GESTURES
2610 ALOGD("Gestures: TAP finished");
2611#endif
2612 *outFinishPreviousGesture = true;
2613
2614 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002615 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002616 mPointerGesture.currentGestureIdBits.clear();
2617
2618 mPointerVelocityControl.reset();
2619 return true;
2620 }
2621 }
2622
2623 // We did not handle this timeout.
2624 return false;
2625 }
2626
2627 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2628 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2629
2630 // Update the velocity tracker.
2631 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002632 std::vector<VelocityTracker::Position> positions;
2633 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002634 uint32_t id = idBits.clearFirstMarkedBit();
2635 const RawPointerData::Pointer& pointer =
2636 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002637 float x = pointer.x * mPointerXMovementScale;
2638 float y = pointer.y * mPointerYMovementScale;
2639 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002640 }
2641 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2642 positions);
2643 }
2644
2645 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2646 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002647 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2648 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2649 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002650 mPointerGesture.resetTap();
2651 }
2652
2653 // Pick a new active touch id if needed.
2654 // Choose an arbitrary pointer that just went down, if there is one.
2655 // Otherwise choose an arbitrary remaining pointer.
2656 // This guarantees we always have an active touch id when there is at least one pointer.
2657 // We keep the same active touch id for as long as possible.
2658 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2659 int32_t activeTouchId = lastActiveTouchId;
2660 if (activeTouchId < 0) {
2661 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2662 activeTouchId = mPointerGesture.activeTouchId =
2663 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2664 mPointerGesture.firstTouchTime = when;
2665 }
2666 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2667 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2668 activeTouchId = mPointerGesture.activeTouchId =
2669 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2670 } else {
2671 activeTouchId = mPointerGesture.activeTouchId = -1;
2672 }
2673 }
2674
2675 // Determine whether we are in quiet time.
2676 bool isQuietTime = false;
2677 if (activeTouchId < 0) {
2678 mPointerGesture.resetQuietTime();
2679 } else {
2680 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2681 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002682 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2683 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2684 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002685 currentFingerCount < 2) {
2686 // Enter quiet time when exiting swipe or freeform state.
2687 // This is to prevent accidentally entering the hover state and flinging the
2688 // pointer when finishing a swipe and there is still one pointer left onscreen.
2689 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002690 } else if (mPointerGesture.lastGestureMode ==
2691 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002692 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2693 // Enter quiet time when releasing the button and there are still two or more
2694 // fingers down. This may indicate that one finger was used to press the button
2695 // but it has not gone up yet.
2696 isQuietTime = true;
2697 }
2698 if (isQuietTime) {
2699 mPointerGesture.quietTime = when;
2700 }
2701 }
2702 }
2703
2704 // Switch states based on button and pointer state.
2705 if (isQuietTime) {
2706 // Case 1: Quiet time. (QUIET)
2707#if DEBUG_GESTURES
2708 ALOGD("Gestures: QUIET for next %0.3fms",
2709 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2710#endif
Michael Wright227c5542020-07-02 18:30:52 +01002711 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002712 *outFinishPreviousGesture = true;
2713 }
2714
2715 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002716 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002717 mPointerGesture.currentGestureIdBits.clear();
2718
2719 mPointerVelocityControl.reset();
2720 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2721 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2722 // The pointer follows the active touch point.
2723 // Emit DOWN, MOVE, UP events at the pointer location.
2724 //
2725 // Only the active touch matters; other fingers are ignored. This policy helps
2726 // to handle the case where the user places a second finger on the touch pad
2727 // to apply the necessary force to depress an integrated button below the surface.
2728 // We don't want the second finger to be delivered to applications.
2729 //
2730 // For this to work well, we need to make sure to track the pointer that is really
2731 // active. If the user first puts one finger down to click then adds another
2732 // finger to drag then the active pointer should switch to the finger that is
2733 // being dragged.
2734#if DEBUG_GESTURES
2735 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2736 "currentFingerCount=%d",
2737 activeTouchId, currentFingerCount);
2738#endif
2739 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002740 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002741 *outFinishPreviousGesture = true;
2742 mPointerGesture.activeGestureId = 0;
2743 }
2744
2745 // Switch pointers if needed.
2746 // Find the fastest pointer and follow it.
2747 if (activeTouchId >= 0 && currentFingerCount > 1) {
2748 int32_t bestId = -1;
2749 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2750 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2751 uint32_t id = idBits.clearFirstMarkedBit();
2752 float vx, vy;
2753 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2754 float speed = hypotf(vx, vy);
2755 if (speed > bestSpeed) {
2756 bestId = id;
2757 bestSpeed = speed;
2758 }
2759 }
2760 }
2761 if (bestId >= 0 && bestId != activeTouchId) {
2762 mPointerGesture.activeTouchId = activeTouchId = bestId;
2763#if DEBUG_GESTURES
2764 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2765 "bestId=%d, bestSpeed=%0.3f",
2766 bestId, bestSpeed);
2767#endif
2768 }
2769 }
2770
2771 float deltaX = 0, deltaY = 0;
2772 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2773 const RawPointerData::Pointer& currentPointer =
2774 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2775 const RawPointerData::Pointer& lastPointer =
2776 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2777 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2778 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2779
2780 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2781 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2782
2783 // Move the pointer using a relative motion.
2784 // When using spots, the click will occur at the position of the anchor
2785 // spot and all other spots will move there.
2786 mPointerController->move(deltaX, deltaY);
2787 } else {
2788 mPointerVelocityControl.reset();
2789 }
2790
2791 float x, y;
2792 mPointerController->getPosition(&x, &y);
2793
Michael Wright227c5542020-07-02 18:30:52 +01002794 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 mPointerGesture.currentGestureIdBits.clear();
2796 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2797 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2798 mPointerGesture.currentGestureProperties[0].clear();
2799 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2800 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2801 mPointerGesture.currentGestureCoords[0].clear();
2802 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2803 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2804 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2805 } else if (currentFingerCount == 0) {
2806 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002807 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002808 *outFinishPreviousGesture = true;
2809 }
2810
2811 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2812 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2813 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002814 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2815 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002816 lastFingerCount == 1) {
2817 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2818 float x, y;
2819 mPointerController->getPosition(&x, &y);
2820 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2821 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2822#if DEBUG_GESTURES
2823 ALOGD("Gestures: TAP");
2824#endif
2825
2826 mPointerGesture.tapUpTime = when;
2827 getContext()->requestTimeoutAtTime(when +
2828 mConfig.pointerGestureTapDragInterval);
2829
2830 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002831 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002832 mPointerGesture.currentGestureIdBits.clear();
2833 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2834 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2835 mPointerGesture.currentGestureProperties[0].clear();
2836 mPointerGesture.currentGestureProperties[0].id =
2837 mPointerGesture.activeGestureId;
2838 mPointerGesture.currentGestureProperties[0].toolType =
2839 AMOTION_EVENT_TOOL_TYPE_FINGER;
2840 mPointerGesture.currentGestureCoords[0].clear();
2841 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2842 mPointerGesture.tapX);
2843 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2844 mPointerGesture.tapY);
2845 mPointerGesture.currentGestureCoords[0]
2846 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2847
2848 tapped = true;
2849 } else {
2850#if DEBUG_GESTURES
2851 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2852 y - mPointerGesture.tapY);
2853#endif
2854 }
2855 } else {
2856#if DEBUG_GESTURES
2857 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2858 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2859 (when - mPointerGesture.tapDownTime) * 0.000001f);
2860 } else {
2861 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2862 }
2863#endif
2864 }
2865 }
2866
2867 mPointerVelocityControl.reset();
2868
2869 if (!tapped) {
2870#if DEBUG_GESTURES
2871 ALOGD("Gestures: NEUTRAL");
2872#endif
2873 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002874 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 mPointerGesture.currentGestureIdBits.clear();
2876 }
2877 } else if (currentFingerCount == 1) {
2878 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2879 // The pointer follows the active touch point.
2880 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2881 // When in TAP_DRAG, emit MOVE events at the pointer location.
2882 ALOG_ASSERT(activeTouchId >= 0);
2883
Michael Wright227c5542020-07-02 18:30:52 +01002884 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2885 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2887 float x, y;
2888 mPointerController->getPosition(&x, &y);
2889 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2890 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002891 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 } else {
2893#if DEBUG_GESTURES
2894 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2895 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2896#endif
2897 }
2898 } else {
2899#if DEBUG_GESTURES
2900 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2901 (when - mPointerGesture.tapUpTime) * 0.000001f);
2902#endif
2903 }
Michael Wright227c5542020-07-02 18:30:52 +01002904 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2905 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906 }
2907
2908 float deltaX = 0, deltaY = 0;
2909 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2910 const RawPointerData::Pointer& currentPointer =
2911 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2912 const RawPointerData::Pointer& lastPointer =
2913 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2914 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2915 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2916
2917 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2918 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2919
2920 // Move the pointer using a relative motion.
2921 // When using spots, the hover or drag will occur at the position of the anchor spot.
2922 mPointerController->move(deltaX, deltaY);
2923 } else {
2924 mPointerVelocityControl.reset();
2925 }
2926
2927 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002928 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002929#if DEBUG_GESTURES
2930 ALOGD("Gestures: TAP_DRAG");
2931#endif
2932 down = true;
2933 } else {
2934#if DEBUG_GESTURES
2935 ALOGD("Gestures: HOVER");
2936#endif
Michael Wright227c5542020-07-02 18:30:52 +01002937 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002938 *outFinishPreviousGesture = true;
2939 }
2940 mPointerGesture.activeGestureId = 0;
2941 down = false;
2942 }
2943
2944 float x, y;
2945 mPointerController->getPosition(&x, &y);
2946
2947 mPointerGesture.currentGestureIdBits.clear();
2948 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2949 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2950 mPointerGesture.currentGestureProperties[0].clear();
2951 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2952 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2953 mPointerGesture.currentGestureCoords[0].clear();
2954 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2955 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2956 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2957 down ? 1.0f : 0.0f);
2958
2959 if (lastFingerCount == 0 && currentFingerCount != 0) {
2960 mPointerGesture.resetTap();
2961 mPointerGesture.tapDownTime = when;
2962 mPointerGesture.tapX = x;
2963 mPointerGesture.tapY = y;
2964 }
2965 } else {
2966 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2967 // We need to provide feedback for each finger that goes down so we cannot wait
2968 // for the fingers to move before deciding what to do.
2969 //
2970 // The ambiguous case is deciding what to do when there are two fingers down but they
2971 // have not moved enough to determine whether they are part of a drag or part of a
2972 // freeform gesture, or just a press or long-press at the pointer location.
2973 //
2974 // When there are two fingers we start with the PRESS hypothesis and we generate a
2975 // down at the pointer location.
2976 //
2977 // When the two fingers move enough or when additional fingers are added, we make
2978 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2979 ALOG_ASSERT(activeTouchId >= 0);
2980
2981 bool settled = when >=
2982 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002983 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2984 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2985 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 *outFinishPreviousGesture = true;
2987 } else if (!settled && currentFingerCount > lastFingerCount) {
2988 // Additional pointers have gone down but not yet settled.
2989 // Reset the gesture.
2990#if DEBUG_GESTURES
2991 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2992 "settle time remaining %0.3fms",
2993 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2994 when) * 0.000001f);
2995#endif
2996 *outCancelPreviousGesture = true;
2997 } else {
2998 // Continue previous gesture.
2999 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3000 }
3001
3002 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003003 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003004 mPointerGesture.activeGestureId = 0;
3005 mPointerGesture.referenceIdBits.clear();
3006 mPointerVelocityControl.reset();
3007
3008 // Use the centroid and pointer location as the reference points for the gesture.
3009#if DEBUG_GESTURES
3010 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3011 "settle time remaining %0.3fms",
3012 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3013 when) * 0.000001f);
3014#endif
3015 mCurrentRawState.rawPointerData
3016 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3017 &mPointerGesture.referenceTouchY);
3018 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3019 &mPointerGesture.referenceGestureY);
3020 }
3021
3022 // Clear the reference deltas for fingers not yet included in the reference calculation.
3023 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3024 ~mPointerGesture.referenceIdBits.value);
3025 !idBits.isEmpty();) {
3026 uint32_t id = idBits.clearFirstMarkedBit();
3027 mPointerGesture.referenceDeltas[id].dx = 0;
3028 mPointerGesture.referenceDeltas[id].dy = 0;
3029 }
3030 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3031
3032 // Add delta for all fingers and calculate a common movement delta.
3033 float commonDeltaX = 0, commonDeltaY = 0;
3034 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3035 mCurrentCookedState.fingerIdBits.value);
3036 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3037 bool first = (idBits == commonIdBits);
3038 uint32_t id = idBits.clearFirstMarkedBit();
3039 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3040 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3041 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3042 delta.dx += cpd.x - lpd.x;
3043 delta.dy += cpd.y - lpd.y;
3044
3045 if (first) {
3046 commonDeltaX = delta.dx;
3047 commonDeltaY = delta.dy;
3048 } else {
3049 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3050 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3051 }
3052 }
3053
3054 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003055 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003056 float dist[MAX_POINTER_ID + 1];
3057 int32_t distOverThreshold = 0;
3058 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3059 uint32_t id = idBits.clearFirstMarkedBit();
3060 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3061 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3062 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3063 distOverThreshold += 1;
3064 }
3065 }
3066
3067 // Only transition when at least two pointers have moved further than
3068 // the minimum distance threshold.
3069 if (distOverThreshold >= 2) {
3070 if (currentFingerCount > 2) {
3071 // There are more than two pointers, switch to FREEFORM.
3072#if DEBUG_GESTURES
3073 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3074 currentFingerCount);
3075#endif
3076 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003077 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003078 } else {
3079 // There are exactly two pointers.
3080 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3081 uint32_t id1 = idBits.clearFirstMarkedBit();
3082 uint32_t id2 = idBits.firstMarkedBit();
3083 const RawPointerData::Pointer& p1 =
3084 mCurrentRawState.rawPointerData.pointerForId(id1);
3085 const RawPointerData::Pointer& p2 =
3086 mCurrentRawState.rawPointerData.pointerForId(id2);
3087 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3088 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3089 // There are two pointers but they are too far apart for a SWIPE,
3090 // switch to FREEFORM.
3091#if DEBUG_GESTURES
3092 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3093 mutualDistance, mPointerGestureMaxSwipeWidth);
3094#endif
3095 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003096 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003097 } else {
3098 // There are two pointers. Wait for both pointers to start moving
3099 // before deciding whether this is a SWIPE or FREEFORM gesture.
3100 float dist1 = dist[id1];
3101 float dist2 = dist[id2];
3102 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3103 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3104 // Calculate the dot product of the displacement vectors.
3105 // When the vectors are oriented in approximately the same direction,
3106 // the angle betweeen them is near zero and the cosine of the angle
3107 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3108 // mag(v2).
3109 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3110 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3111 float dx1 = delta1.dx * mPointerXZoomScale;
3112 float dy1 = delta1.dy * mPointerYZoomScale;
3113 float dx2 = delta2.dx * mPointerXZoomScale;
3114 float dy2 = delta2.dy * mPointerYZoomScale;
3115 float dot = dx1 * dx2 + dy1 * dy2;
3116 float cosine = dot / (dist1 * dist2); // denominator always > 0
3117 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3118 // Pointers are moving in the same direction. Switch to SWIPE.
3119#if DEBUG_GESTURES
3120 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3121 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3122 "cosine %0.3f >= %0.3f",
3123 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3124 mConfig.pointerGestureMultitouchMinDistance, cosine,
3125 mConfig.pointerGestureSwipeTransitionAngleCosine);
3126#endif
Michael Wright227c5542020-07-02 18:30:52 +01003127 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003128 } else {
3129 // Pointers are moving in different directions. Switch to FREEFORM.
3130#if DEBUG_GESTURES
3131 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3132 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3133 "cosine %0.3f < %0.3f",
3134 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3135 mConfig.pointerGestureMultitouchMinDistance, cosine,
3136 mConfig.pointerGestureSwipeTransitionAngleCosine);
3137#endif
3138 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003139 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003140 }
3141 }
3142 }
3143 }
3144 }
Michael Wright227c5542020-07-02 18:30:52 +01003145 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003146 // Switch from SWIPE to FREEFORM if additional pointers go down.
3147 // Cancel previous gesture.
3148 if (currentFingerCount > 2) {
3149#if DEBUG_GESTURES
3150 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3151 currentFingerCount);
3152#endif
3153 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003154 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003155 }
3156 }
3157
3158 // Move the reference points based on the overall group motion of the fingers
3159 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003160 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003161 (commonDeltaX || commonDeltaY)) {
3162 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3163 uint32_t id = idBits.clearFirstMarkedBit();
3164 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3165 delta.dx = 0;
3166 delta.dy = 0;
3167 }
3168
3169 mPointerGesture.referenceTouchX += commonDeltaX;
3170 mPointerGesture.referenceTouchY += commonDeltaY;
3171
3172 commonDeltaX *= mPointerXMovementScale;
3173 commonDeltaY *= mPointerYMovementScale;
3174
3175 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3176 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3177
3178 mPointerGesture.referenceGestureX += commonDeltaX;
3179 mPointerGesture.referenceGestureY += commonDeltaY;
3180 }
3181
3182 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003183 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3184 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003185 // PRESS or SWIPE mode.
3186#if DEBUG_GESTURES
3187 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3188 "activeGestureId=%d, currentTouchPointerCount=%d",
3189 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3190#endif
3191 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3192
3193 mPointerGesture.currentGestureIdBits.clear();
3194 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3195 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3196 mPointerGesture.currentGestureProperties[0].clear();
3197 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3198 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3199 mPointerGesture.currentGestureCoords[0].clear();
3200 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3201 mPointerGesture.referenceGestureX);
3202 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3203 mPointerGesture.referenceGestureY);
3204 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003205 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003206 // FREEFORM mode.
3207#if DEBUG_GESTURES
3208 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3209 "activeGestureId=%d, currentTouchPointerCount=%d",
3210 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3211#endif
3212 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3213
3214 mPointerGesture.currentGestureIdBits.clear();
3215
3216 BitSet32 mappedTouchIdBits;
3217 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003218 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003219 // Initially, assign the active gesture id to the active touch point
3220 // if there is one. No other touch id bits are mapped yet.
3221 if (!*outCancelPreviousGesture) {
3222 mappedTouchIdBits.markBit(activeTouchId);
3223 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3224 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3225 mPointerGesture.activeGestureId;
3226 } else {
3227 mPointerGesture.activeGestureId = -1;
3228 }
3229 } else {
3230 // Otherwise, assume we mapped all touches from the previous frame.
3231 // Reuse all mappings that are still applicable.
3232 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3233 mCurrentCookedState.fingerIdBits.value;
3234 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3235
3236 // Check whether we need to choose a new active gesture id because the
3237 // current went went up.
3238 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3239 ~mCurrentCookedState.fingerIdBits.value);
3240 !upTouchIdBits.isEmpty();) {
3241 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3242 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3243 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3244 mPointerGesture.activeGestureId = -1;
3245 break;
3246 }
3247 }
3248 }
3249
3250#if DEBUG_GESTURES
3251 ALOGD("Gestures: FREEFORM follow up "
3252 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3253 "activeGestureId=%d",
3254 mappedTouchIdBits.value, usedGestureIdBits.value,
3255 mPointerGesture.activeGestureId);
3256#endif
3257
3258 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3259 for (uint32_t i = 0; i < currentFingerCount; i++) {
3260 uint32_t touchId = idBits.clearFirstMarkedBit();
3261 uint32_t gestureId;
3262 if (!mappedTouchIdBits.hasBit(touchId)) {
3263 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3264 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3265#if DEBUG_GESTURES
3266 ALOGD("Gestures: FREEFORM "
3267 "new mapping for touch id %d -> gesture id %d",
3268 touchId, gestureId);
3269#endif
3270 } else {
3271 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3272#if DEBUG_GESTURES
3273 ALOGD("Gestures: FREEFORM "
3274 "existing mapping for touch id %d -> gesture id %d",
3275 touchId, gestureId);
3276#endif
3277 }
3278 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3279 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3280
3281 const RawPointerData::Pointer& pointer =
3282 mCurrentRawState.rawPointerData.pointerForId(touchId);
3283 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3284 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3285 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3286
3287 mPointerGesture.currentGestureProperties[i].clear();
3288 mPointerGesture.currentGestureProperties[i].id = gestureId;
3289 mPointerGesture.currentGestureProperties[i].toolType =
3290 AMOTION_EVENT_TOOL_TYPE_FINGER;
3291 mPointerGesture.currentGestureCoords[i].clear();
3292 mPointerGesture.currentGestureCoords[i]
3293 .setAxisValue(AMOTION_EVENT_AXIS_X,
3294 mPointerGesture.referenceGestureX + deltaX);
3295 mPointerGesture.currentGestureCoords[i]
3296 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3297 mPointerGesture.referenceGestureY + deltaY);
3298 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3299 1.0f);
3300 }
3301
3302 if (mPointerGesture.activeGestureId < 0) {
3303 mPointerGesture.activeGestureId =
3304 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3305#if DEBUG_GESTURES
3306 ALOGD("Gestures: FREEFORM new "
3307 "activeGestureId=%d",
3308 mPointerGesture.activeGestureId);
3309#endif
3310 }
3311 }
3312 }
3313
3314 mPointerController->setButtonState(mCurrentRawState.buttonState);
3315
3316#if DEBUG_GESTURES
3317 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3318 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3319 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3320 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3321 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3322 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3323 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3324 uint32_t id = idBits.clearFirstMarkedBit();
3325 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3326 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3327 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3328 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3329 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3330 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3331 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3332 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3333 }
3334 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3335 uint32_t id = idBits.clearFirstMarkedBit();
3336 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3337 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3338 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3339 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3340 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3341 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3342 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3343 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3344 }
3345#endif
3346 return true;
3347}
3348
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003349void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003350 mPointerSimple.currentCoords.clear();
3351 mPointerSimple.currentProperties.clear();
3352
3353 bool down, hovering;
3354 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3355 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3356 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3357 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3358 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3359 mPointerController->setPosition(x, y);
3360
3361 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3362 down = !hovering;
3363
3364 mPointerController->getPosition(&x, &y);
3365 mPointerSimple.currentCoords.copyFrom(
3366 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3367 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3368 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3369 mPointerSimple.currentProperties.id = 0;
3370 mPointerSimple.currentProperties.toolType =
3371 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3372 } else {
3373 down = false;
3374 hovering = false;
3375 }
3376
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003377 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003378}
3379
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003380void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3381 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003382}
3383
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003384void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003385 mPointerSimple.currentCoords.clear();
3386 mPointerSimple.currentProperties.clear();
3387
3388 bool down, hovering;
3389 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3390 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3391 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3392 float deltaX = 0, deltaY = 0;
3393 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3394 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3395 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3396 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3397 mPointerXMovementScale;
3398 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3399 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3400 mPointerYMovementScale;
3401
3402 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3403 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3404
3405 mPointerController->move(deltaX, deltaY);
3406 } else {
3407 mPointerVelocityControl.reset();
3408 }
3409
3410 down = isPointerDown(mCurrentRawState.buttonState);
3411 hovering = !down;
3412
3413 float x, y;
3414 mPointerController->getPosition(&x, &y);
3415 mPointerSimple.currentCoords.copyFrom(
3416 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3417 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3418 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3419 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3420 hovering ? 0.0f : 1.0f);
3421 mPointerSimple.currentProperties.id = 0;
3422 mPointerSimple.currentProperties.toolType =
3423 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3424 } else {
3425 mPointerVelocityControl.reset();
3426
3427 down = false;
3428 hovering = false;
3429 }
3430
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003431 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003432}
3433
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003434void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3435 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003436
3437 mPointerVelocityControl.reset();
3438}
3439
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003440void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3441 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003442 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003443
3444 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003445 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003446 mPointerController->clearSpots();
3447 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003448 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003449 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003450 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003451 }
Garfield Tan9514d782020-11-10 16:37:23 -08003452 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003453
3454 float xCursorPosition;
3455 float yCursorPosition;
3456 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3457
3458 if (mPointerSimple.down && !down) {
3459 mPointerSimple.down = false;
3460
3461 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003462 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3463 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003464 mLastRawState.buttonState, MotionClassification::NONE,
3465 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3466 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3467 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3468 /* videoFrames */ {});
3469 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003470 }
3471
3472 if (mPointerSimple.hovering && !hovering) {
3473 mPointerSimple.hovering = false;
3474
3475 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003476 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3477 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3478 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003479 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3480 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3481 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3482 /* videoFrames */ {});
3483 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003484 }
3485
3486 if (down) {
3487 if (!mPointerSimple.down) {
3488 mPointerSimple.down = true;
3489 mPointerSimple.downTime = when;
3490
3491 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003492 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003493 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3494 metaState, mCurrentRawState.buttonState,
3495 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3496 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3497 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3498 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3499 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003500 }
3501
3502 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003503 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3504 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003505 mCurrentRawState.buttonState, MotionClassification::NONE,
3506 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3507 &mPointerSimple.currentCoords, mOrientedXPrecision,
3508 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3509 mPointerSimple.downTime, /* videoFrames */ {});
3510 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003511 }
3512
3513 if (hovering) {
3514 if (!mPointerSimple.hovering) {
3515 mPointerSimple.hovering = true;
3516
3517 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003518 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003519 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3520 metaState, mCurrentRawState.buttonState,
3521 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3522 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3523 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3524 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3525 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003526 }
3527
3528 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003529 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3530 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3531 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003532 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3533 &mPointerSimple.currentCoords, mOrientedXPrecision,
3534 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3535 mPointerSimple.downTime, /* videoFrames */ {});
3536 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003537 }
3538
3539 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3540 float vscroll = mCurrentRawState.rawVScroll;
3541 float hscroll = mCurrentRawState.rawHScroll;
3542 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3543 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3544
3545 // Send scroll.
3546 PointerCoords pointerCoords;
3547 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3548 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3549 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3550
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003551 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3552 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003553 mCurrentRawState.buttonState, MotionClassification::NONE,
3554 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3555 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3556 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3557 /* videoFrames */ {});
3558 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003559 }
3560
3561 // Save state.
3562 if (down || hovering) {
3563 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3564 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3565 } else {
3566 mPointerSimple.reset();
3567 }
3568}
3569
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003570void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571 mPointerSimple.currentCoords.clear();
3572 mPointerSimple.currentProperties.clear();
3573
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003574 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003575}
3576
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003577void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3578 uint32_t source, int32_t action, int32_t actionButton,
3579 int32_t flags, int32_t metaState, int32_t buttonState,
3580 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003581 const PointerCoords* coords, const uint32_t* idToIndex,
3582 BitSet32 idBits, int32_t changedId, float xPrecision,
3583 float yPrecision, nsecs_t downTime) {
3584 PointerCoords pointerCoords[MAX_POINTERS];
3585 PointerProperties pointerProperties[MAX_POINTERS];
3586 uint32_t pointerCount = 0;
3587 while (!idBits.isEmpty()) {
3588 uint32_t id = idBits.clearFirstMarkedBit();
3589 uint32_t index = idToIndex[id];
3590 pointerProperties[pointerCount].copyFrom(properties[index]);
3591 pointerCoords[pointerCount].copyFrom(coords[index]);
3592
3593 if (changedId >= 0 && id == uint32_t(changedId)) {
3594 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3595 }
3596
3597 pointerCount += 1;
3598 }
3599
3600 ALOG_ASSERT(pointerCount != 0);
3601
3602 if (changedId >= 0 && pointerCount == 1) {
3603 // Replace initial down and final up action.
3604 // We can compare the action without masking off the changed pointer index
3605 // because we know the index is 0.
3606 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3607 action = AMOTION_EVENT_ACTION_DOWN;
3608 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003609 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3610 action = AMOTION_EVENT_ACTION_CANCEL;
3611 } else {
3612 action = AMOTION_EVENT_ACTION_UP;
3613 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003614 } else {
3615 // Can't happen.
3616 ALOG_ASSERT(false);
3617 }
3618 }
3619 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3620 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003621 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003622 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3623 }
3624 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3625 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003626 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003627 std::for_each(frames.begin(), frames.end(),
3628 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003629 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3630 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003631 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3632 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3633 downTime, std::move(frames));
3634 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003635}
3636
3637bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3638 const PointerCoords* inCoords,
3639 const uint32_t* inIdToIndex,
3640 PointerProperties* outProperties,
3641 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3642 BitSet32 idBits) const {
3643 bool changed = false;
3644 while (!idBits.isEmpty()) {
3645 uint32_t id = idBits.clearFirstMarkedBit();
3646 uint32_t inIndex = inIdToIndex[id];
3647 uint32_t outIndex = outIdToIndex[id];
3648
3649 const PointerProperties& curInProperties = inProperties[inIndex];
3650 const PointerCoords& curInCoords = inCoords[inIndex];
3651 PointerProperties& curOutProperties = outProperties[outIndex];
3652 PointerCoords& curOutCoords = outCoords[outIndex];
3653
3654 if (curInProperties != curOutProperties) {
3655 curOutProperties.copyFrom(curInProperties);
3656 changed = true;
3657 }
3658
3659 if (curInCoords != curOutCoords) {
3660 curOutCoords.copyFrom(curInCoords);
3661 changed = true;
3662 }
3663 }
3664 return changed;
3665}
3666
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003667void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3668 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3669 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003670}
3671
Arthur Hung4197f6b2020-03-16 15:39:59 +08003672// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003673void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003674 // Scale to surface coordinate.
3675 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3676 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3677
arthurhunga36b28e2020-12-29 20:28:15 +08003678 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3679 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3680
Arthur Hung4197f6b2020-03-16 15:39:59 +08003681 // Rotate to surface coordinate.
3682 // 0 - no swap and reverse.
3683 // 90 - swap x/y and reverse y.
3684 // 180 - reverse x, y.
3685 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003686 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003687 case DISPLAY_ORIENTATION_0:
3688 x = xScaled + mXTranslate;
3689 y = yScaled + mYTranslate;
3690 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003691 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003692 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003693 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003694 break;
3695 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003696 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3697 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003698 break;
3699 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003700 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003701 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003702 break;
3703 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003704 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003705 }
3706}
3707
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003708bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003709 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3710 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3711
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003712 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003713 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003714 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003715 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003716}
3717
3718const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3719 for (const VirtualKey& virtualKey : mVirtualKeys) {
3720#if DEBUG_VIRTUAL_KEYS
3721 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3722 "left=%d, top=%d, right=%d, bottom=%d",
3723 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3724 virtualKey.hitRight, virtualKey.hitBottom);
3725#endif
3726
3727 if (virtualKey.isHit(x, y)) {
3728 return &virtualKey;
3729 }
3730 }
3731
3732 return nullptr;
3733}
3734
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003735void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3736 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3737 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003738
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003739 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003740
3741 if (currentPointerCount == 0) {
3742 // No pointers to assign.
3743 return;
3744 }
3745
3746 if (lastPointerCount == 0) {
3747 // All pointers are new.
3748 for (uint32_t i = 0; i < currentPointerCount; i++) {
3749 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003750 current.rawPointerData.pointers[i].id = id;
3751 current.rawPointerData.idToIndex[id] = i;
3752 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003753 }
3754 return;
3755 }
3756
3757 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003758 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003759 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003760 uint32_t id = last.rawPointerData.pointers[0].id;
3761 current.rawPointerData.pointers[0].id = id;
3762 current.rawPointerData.idToIndex[id] = 0;
3763 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003764 return;
3765 }
3766
3767 // General case.
3768 // We build a heap of squared euclidean distances between current and last pointers
3769 // associated with the current and last pointer indices. Then, we find the best
3770 // match (by distance) for each current pointer.
3771 // The pointers must have the same tool type but it is possible for them to
3772 // transition from hovering to touching or vice-versa while retaining the same id.
3773 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3774
3775 uint32_t heapSize = 0;
3776 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3777 currentPointerIndex++) {
3778 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3779 lastPointerIndex++) {
3780 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003781 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003782 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003783 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003784 if (currentPointer.toolType == lastPointer.toolType) {
3785 int64_t deltaX = currentPointer.x - lastPointer.x;
3786 int64_t deltaY = currentPointer.y - lastPointer.y;
3787
3788 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3789
3790 // Insert new element into the heap (sift up).
3791 heap[heapSize].currentPointerIndex = currentPointerIndex;
3792 heap[heapSize].lastPointerIndex = lastPointerIndex;
3793 heap[heapSize].distance = distance;
3794 heapSize += 1;
3795 }
3796 }
3797 }
3798
3799 // Heapify
3800 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3801 startIndex -= 1;
3802 for (uint32_t parentIndex = startIndex;;) {
3803 uint32_t childIndex = parentIndex * 2 + 1;
3804 if (childIndex >= heapSize) {
3805 break;
3806 }
3807
3808 if (childIndex + 1 < heapSize &&
3809 heap[childIndex + 1].distance < heap[childIndex].distance) {
3810 childIndex += 1;
3811 }
3812
3813 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3814 break;
3815 }
3816
3817 swap(heap[parentIndex], heap[childIndex]);
3818 parentIndex = childIndex;
3819 }
3820 }
3821
3822#if DEBUG_POINTER_ASSIGNMENT
3823 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3824 for (size_t i = 0; i < heapSize; i++) {
3825 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3826 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3827 }
3828#endif
3829
3830 // Pull matches out by increasing order of distance.
3831 // To avoid reassigning pointers that have already been matched, the loop keeps track
3832 // of which last and current pointers have been matched using the matchedXXXBits variables.
3833 // It also tracks the used pointer id bits.
3834 BitSet32 matchedLastBits(0);
3835 BitSet32 matchedCurrentBits(0);
3836 BitSet32 usedIdBits(0);
3837 bool first = true;
3838 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3839 while (heapSize > 0) {
3840 if (first) {
3841 // The first time through the loop, we just consume the root element of
3842 // the heap (the one with smallest distance).
3843 first = false;
3844 } else {
3845 // Previous iterations consumed the root element of the heap.
3846 // Pop root element off of the heap (sift down).
3847 heap[0] = heap[heapSize];
3848 for (uint32_t parentIndex = 0;;) {
3849 uint32_t childIndex = parentIndex * 2 + 1;
3850 if (childIndex >= heapSize) {
3851 break;
3852 }
3853
3854 if (childIndex + 1 < heapSize &&
3855 heap[childIndex + 1].distance < heap[childIndex].distance) {
3856 childIndex += 1;
3857 }
3858
3859 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3860 break;
3861 }
3862
3863 swap(heap[parentIndex], heap[childIndex]);
3864 parentIndex = childIndex;
3865 }
3866
3867#if DEBUG_POINTER_ASSIGNMENT
3868 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003869 for (size_t j = 0; j < heapSize; j++) {
3870 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3871 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003872 }
3873#endif
3874 }
3875
3876 heapSize -= 1;
3877
3878 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3879 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3880
3881 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3882 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3883
3884 matchedCurrentBits.markBit(currentPointerIndex);
3885 matchedLastBits.markBit(lastPointerIndex);
3886
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003887 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3888 current.rawPointerData.pointers[currentPointerIndex].id = id;
3889 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3890 current.rawPointerData.markIdBit(id,
3891 current.rawPointerData.isHovering(
3892 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003893 usedIdBits.markBit(id);
3894
3895#if DEBUG_POINTER_ASSIGNMENT
3896 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3897 ", distance=%" PRIu64,
3898 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3899#endif
3900 break;
3901 }
3902 }
3903
3904 // Assign fresh ids to pointers that were not matched in the process.
3905 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3906 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3907 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3908
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003909 current.rawPointerData.pointers[currentPointerIndex].id = id;
3910 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3911 current.rawPointerData.markIdBit(id,
3912 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003913
3914#if DEBUG_POINTER_ASSIGNMENT
3915 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3916#endif
3917 }
3918}
3919
3920int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3921 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3922 return AKEY_STATE_VIRTUAL;
3923 }
3924
3925 for (const VirtualKey& virtualKey : mVirtualKeys) {
3926 if (virtualKey.keyCode == keyCode) {
3927 return AKEY_STATE_UP;
3928 }
3929 }
3930
3931 return AKEY_STATE_UNKNOWN;
3932}
3933
3934int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3935 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3936 return AKEY_STATE_VIRTUAL;
3937 }
3938
3939 for (const VirtualKey& virtualKey : mVirtualKeys) {
3940 if (virtualKey.scanCode == scanCode) {
3941 return AKEY_STATE_UP;
3942 }
3943 }
3944
3945 return AKEY_STATE_UNKNOWN;
3946}
3947
3948bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3949 const int32_t* keyCodes, uint8_t* outFlags) {
3950 for (const VirtualKey& virtualKey : mVirtualKeys) {
3951 for (size_t i = 0; i < numCodes; i++) {
3952 if (virtualKey.keyCode == keyCodes[i]) {
3953 outFlags[i] = 1;
3954 }
3955 }
3956 }
3957
3958 return true;
3959}
3960
3961std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3962 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003963 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003964 return std::make_optional(mPointerController->getDisplayId());
3965 } else {
3966 return std::make_optional(mViewport.displayId);
3967 }
3968 }
3969 return std::nullopt;
3970}
3971
3972} // namespace android