blob: 1a17bef399804c6f11bd17fecddf152bbb94314e [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 Vishniakoucec3f6a2020-11-10 15:42:39 -0600400 getContext()->notifyDeviceReset(when, getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700401 }
402}
403
404void TouchInputMapper::resolveExternalStylusPresence() {
405 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800406 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700407 mExternalStylusConnected = !devices.empty();
408
409 if (!mExternalStylusConnected) {
410 resetExternalStylus();
411 }
412}
413
414void TouchInputMapper::configureParameters() {
415 // Use the pointer presentation mode for devices that do not support distinct
416 // multitouch. The spot-based presentation relies on being able to accurately
417 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100419 ? Parameters::GestureMode::SINGLE_TOUCH
420 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421
422 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800423 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
424 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700425 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100426 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700427 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100428 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700429 } else if (gestureModeString != "default") {
430 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
431 }
432 }
433
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800434 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700435 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100436 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800437 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100439 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800440 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
441 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700442 // The device is a cursor device with a touch pad attached.
443 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100444 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700445 } else {
446 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100447 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448 }
449
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800450 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700451
452 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800453 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
454 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100456 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100458 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100460 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700461 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100462 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463 } else if (deviceTypeString != "default") {
464 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
465 }
466 }
467
Michael Wright227c5542020-07-02 18:30:52 +0100468 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800469 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
470 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700471
472 mParameters.hasAssociatedDisplay = false;
473 mParameters.associatedDisplayIsExternal = false;
474 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100475 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
476 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700477 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100478 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800479 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700480 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800481 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
482 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700483 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
484 }
485 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800486 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700487 mParameters.hasAssociatedDisplay = true;
488 }
489
490 // Initial downs on external touch devices should wake the device.
491 // Normally we don't do this for internal touch screens to prevent them from waking
492 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800493 mParameters.wake = getDeviceContext().isExternal();
494 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700495}
496
497void TouchInputMapper::dumpParameters(std::string& dump) {
498 dump += INDENT3 "Parameters:\n";
499
Chris Yea03dd232020-09-08 19:21:09 -0700500 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700501
Chris Yea03dd232020-09-08 19:21:09 -0700502 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700503
504 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
505 "displayId='%s'\n",
506 toString(mParameters.hasAssociatedDisplay),
507 toString(mParameters.associatedDisplayIsExternal),
508 mParameters.uniqueDisplayId.c_str());
509 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
510}
511
512void TouchInputMapper::configureRawPointerAxes() {
513 mRawPointerAxes.clear();
514}
515
516void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
517 dump += INDENT3 "Raw Touch Axes:\n";
518 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
531}
532
533bool TouchInputMapper::hasExternalStylus() const {
534 return mExternalStylusConnected;
535}
536
537/**
538 * Determine which DisplayViewport to use.
539 * 1. If display port is specified, return the matching viewport. If matching viewport not
540 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800541 * 2. Always use the suggested viewport from WindowManagerService for pointers.
542 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700543 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800544 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700545 */
546std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800547 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800548 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700549 if (displayPort) {
550 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800551 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700552 }
553
Michael Wright227c5542020-07-02 18:30:52 +0100554 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800555 std::optional<DisplayViewport> viewport =
556 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
557 if (viewport) {
558 return viewport;
559 } else {
560 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
561 mConfig.defaultPointerDisplayId);
562 }
563 }
564
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700565 // Check if uniqueDisplayId is specified in idc file.
566 if (!mParameters.uniqueDisplayId.empty()) {
567 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
568 }
569
570 ViewportType viewportTypeToUse;
571 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100572 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700573 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100574 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700575 }
576
577 std::optional<DisplayViewport> viewport =
578 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100579 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700580 ALOGW("Input device %s should be associated with external display, "
581 "fallback to internal one for the external viewport is not found.",
582 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100583 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700584 }
585
586 return viewport;
587 }
588
589 // No associated display, return a non-display viewport.
590 DisplayViewport newViewport;
591 // Raw width and height in the natural orientation.
592 int32_t rawWidth = mRawPointerAxes.getRawWidth();
593 int32_t rawHeight = mRawPointerAxes.getRawHeight();
594 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
595 return std::make_optional(newViewport);
596}
597
598void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100599 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700600
601 resolveExternalStylusPresence();
602
603 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100604 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800605 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700606 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100607 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700608 if (hasStylus()) {
609 mSource |= AINPUT_SOURCE_STYLUS;
610 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800611 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700612 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100613 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700614 if (hasStylus()) {
615 mSource |= AINPUT_SOURCE_STYLUS;
616 }
617 if (hasExternalStylus()) {
618 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
619 }
Michael Wright227c5542020-07-02 18:30:52 +0100620 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700621 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100622 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700623 } else {
624 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100625 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700626 }
627
628 // Ensure we have valid X and Y axes.
629 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
630 ALOGW("Touch device '%s' did not report support for X or Y axis! "
631 "The device will be inoperable.",
632 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100633 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700634 return;
635 }
636
637 // Get associated display dimensions.
638 std::optional<DisplayViewport> newViewport = findViewport();
639 if (!newViewport) {
640 ALOGI("Touch device '%s' could not query the properties of its associated "
641 "display. The device will be inoperable until the display size "
642 "becomes available.",
643 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100644 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700645 return;
646 }
647
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000648 if (!newViewport->isActive) {
649 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
650 getDeviceName().c_str(), getDeviceId());
651 mDeviceMode = DeviceMode::DISABLED;
652 return;
653 }
654
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700655 // Raw width and height in the natural orientation.
656 int32_t rawWidth = mRawPointerAxes.getRawWidth();
657 int32_t rawHeight = mRawPointerAxes.getRawHeight();
658
659 bool viewportChanged = mViewport != *newViewport;
660 if (viewportChanged) {
661 mViewport = *newViewport;
662
Michael Wright227c5542020-07-02 18:30:52 +0100663 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700664 // Convert rotated viewport to natural surface coordinates.
665 int32_t naturalLogicalWidth, naturalLogicalHeight;
666 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
667 int32_t naturalPhysicalLeft, naturalPhysicalTop;
668 int32_t naturalDeviceWidth, naturalDeviceHeight;
669 switch (mViewport.orientation) {
670 case DISPLAY_ORIENTATION_90:
671 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
672 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
673 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
674 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800675 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700676 naturalPhysicalTop = mViewport.physicalLeft;
677 naturalDeviceWidth = mViewport.deviceHeight;
678 naturalDeviceHeight = mViewport.deviceWidth;
679 break;
680 case DISPLAY_ORIENTATION_180:
681 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
682 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
683 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
684 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
685 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
686 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
687 naturalDeviceWidth = mViewport.deviceWidth;
688 naturalDeviceHeight = mViewport.deviceHeight;
689 break;
690 case DISPLAY_ORIENTATION_270:
691 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
692 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
693 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
694 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
695 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800696 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700697 naturalDeviceWidth = mViewport.deviceHeight;
698 naturalDeviceHeight = mViewport.deviceWidth;
699 break;
700 case DISPLAY_ORIENTATION_0:
701 default:
702 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
703 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
704 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
705 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
706 naturalPhysicalLeft = mViewport.physicalLeft;
707 naturalPhysicalTop = mViewport.physicalTop;
708 naturalDeviceWidth = mViewport.deviceWidth;
709 naturalDeviceHeight = mViewport.deviceHeight;
710 break;
711 }
712
713 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
714 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
715 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
716 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
717 }
718
719 mPhysicalWidth = naturalPhysicalWidth;
720 mPhysicalHeight = naturalPhysicalHeight;
721 mPhysicalLeft = naturalPhysicalLeft;
722 mPhysicalTop = naturalPhysicalTop;
723
Arthur Hung4197f6b2020-03-16 15:39:59 +0800724 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
725 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700726 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
727 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800728 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
729 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700730
731 mSurfaceOrientation =
732 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
733 } else {
734 mPhysicalWidth = rawWidth;
735 mPhysicalHeight = rawHeight;
736 mPhysicalLeft = 0;
737 mPhysicalTop = 0;
738
Arthur Hung4197f6b2020-03-16 15:39:59 +0800739 mRawSurfaceWidth = rawWidth;
740 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700741 mSurfaceLeft = 0;
742 mSurfaceTop = 0;
743 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
744 }
745 }
746
747 // If moving between pointer modes, need to reset some state.
748 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
749 if (deviceModeChanged) {
750 mOrientedRanges.clear();
751 }
752
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800753 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
754 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100755 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800756 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
757 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800758 if (mPointerController == nullptr) {
759 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700760 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800761 if (mConfig.pointerCapture) {
762 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
763 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700764 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100765 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700766 }
767
768 if (viewportChanged || deviceModeChanged) {
769 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
770 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800771 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700772 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
773
774 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800775 mXScale = float(mRawSurfaceWidth) / rawWidth;
776 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700777 mXTranslate = -mSurfaceLeft;
778 mYTranslate = -mSurfaceTop;
779 mXPrecision = 1.0f / mXScale;
780 mYPrecision = 1.0f / mYScale;
781
782 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
783 mOrientedRanges.x.source = mSource;
784 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
785 mOrientedRanges.y.source = mSource;
786
787 configureVirtualKeys();
788
789 // Scale factor for terms that are not oriented in a particular axis.
790 // If the pixels are square then xScale == yScale otherwise we fake it
791 // by choosing an average.
792 mGeometricScale = avg(mXScale, mYScale);
793
794 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800795 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700796
797 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100798 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700799 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
800 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
801 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
802 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
803 } else {
804 mSizeScale = 0.0f;
805 }
806
807 mOrientedRanges.haveTouchSize = true;
808 mOrientedRanges.haveToolSize = true;
809 mOrientedRanges.haveSize = true;
810
811 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
812 mOrientedRanges.touchMajor.source = mSource;
813 mOrientedRanges.touchMajor.min = 0;
814 mOrientedRanges.touchMajor.max = diagonalSize;
815 mOrientedRanges.touchMajor.flat = 0;
816 mOrientedRanges.touchMajor.fuzz = 0;
817 mOrientedRanges.touchMajor.resolution = 0;
818
819 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
820 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
821
822 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
823 mOrientedRanges.toolMajor.source = mSource;
824 mOrientedRanges.toolMajor.min = 0;
825 mOrientedRanges.toolMajor.max = diagonalSize;
826 mOrientedRanges.toolMajor.flat = 0;
827 mOrientedRanges.toolMajor.fuzz = 0;
828 mOrientedRanges.toolMajor.resolution = 0;
829
830 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
831 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
832
833 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
834 mOrientedRanges.size.source = mSource;
835 mOrientedRanges.size.min = 0;
836 mOrientedRanges.size.max = 1.0;
837 mOrientedRanges.size.flat = 0;
838 mOrientedRanges.size.fuzz = 0;
839 mOrientedRanges.size.resolution = 0;
840 } else {
841 mSizeScale = 0.0f;
842 }
843
844 // Pressure factors.
845 mPressureScale = 0;
846 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100847 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
848 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700849 if (mCalibration.havePressureScale) {
850 mPressureScale = mCalibration.pressureScale;
851 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
852 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
853 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
854 }
855 }
856
857 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
858 mOrientedRanges.pressure.source = mSource;
859 mOrientedRanges.pressure.min = 0;
860 mOrientedRanges.pressure.max = pressureMax;
861 mOrientedRanges.pressure.flat = 0;
862 mOrientedRanges.pressure.fuzz = 0;
863 mOrientedRanges.pressure.resolution = 0;
864
865 // Tilt
866 mTiltXCenter = 0;
867 mTiltXScale = 0;
868 mTiltYCenter = 0;
869 mTiltYScale = 0;
870 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
871 if (mHaveTilt) {
872 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
873 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
874 mTiltXScale = M_PI / 180;
875 mTiltYScale = M_PI / 180;
876
877 mOrientedRanges.haveTilt = true;
878
879 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
880 mOrientedRanges.tilt.source = mSource;
881 mOrientedRanges.tilt.min = 0;
882 mOrientedRanges.tilt.max = M_PI_2;
883 mOrientedRanges.tilt.flat = 0;
884 mOrientedRanges.tilt.fuzz = 0;
885 mOrientedRanges.tilt.resolution = 0;
886 }
887
888 // Orientation
889 mOrientationScale = 0;
890 if (mHaveTilt) {
891 mOrientedRanges.haveOrientation = true;
892
893 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
894 mOrientedRanges.orientation.source = mSource;
895 mOrientedRanges.orientation.min = -M_PI;
896 mOrientedRanges.orientation.max = M_PI;
897 mOrientedRanges.orientation.flat = 0;
898 mOrientedRanges.orientation.fuzz = 0;
899 mOrientedRanges.orientation.resolution = 0;
900 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100901 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100903 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 if (mRawPointerAxes.orientation.valid) {
905 if (mRawPointerAxes.orientation.maxValue > 0) {
906 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
907 } else if (mRawPointerAxes.orientation.minValue < 0) {
908 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
909 } else {
910 mOrientationScale = 0;
911 }
912 }
913 }
914
915 mOrientedRanges.haveOrientation = true;
916
917 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
918 mOrientedRanges.orientation.source = mSource;
919 mOrientedRanges.orientation.min = -M_PI_2;
920 mOrientedRanges.orientation.max = M_PI_2;
921 mOrientedRanges.orientation.flat = 0;
922 mOrientedRanges.orientation.fuzz = 0;
923 mOrientedRanges.orientation.resolution = 0;
924 }
925
926 // Distance
927 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100928 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
929 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700930 if (mCalibration.haveDistanceScale) {
931 mDistanceScale = mCalibration.distanceScale;
932 } else {
933 mDistanceScale = 1.0f;
934 }
935 }
936
937 mOrientedRanges.haveDistance = true;
938
939 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
940 mOrientedRanges.distance.source = mSource;
941 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
942 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
943 mOrientedRanges.distance.flat = 0;
944 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
945 mOrientedRanges.distance.resolution = 0;
946 }
947
948 // Compute oriented precision, scales and ranges.
949 // Note that the maximum value reported is an inclusive maximum value so it is one
950 // unit less than the total width or height of surface.
951 switch (mSurfaceOrientation) {
952 case DISPLAY_ORIENTATION_90:
953 case DISPLAY_ORIENTATION_270:
954 mOrientedXPrecision = mYPrecision;
955 mOrientedYPrecision = mXPrecision;
956
957 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800958 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700959 mOrientedRanges.x.flat = 0;
960 mOrientedRanges.x.fuzz = 0;
961 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
962
963 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800964 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700965 mOrientedRanges.y.flat = 0;
966 mOrientedRanges.y.fuzz = 0;
967 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
968 break;
969
970 default:
971 mOrientedXPrecision = mXPrecision;
972 mOrientedYPrecision = mYPrecision;
973
974 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800975 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700976 mOrientedRanges.x.flat = 0;
977 mOrientedRanges.x.fuzz = 0;
978 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
979
980 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800981 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700982 mOrientedRanges.y.flat = 0;
983 mOrientedRanges.y.fuzz = 0;
984 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
985 break;
986 }
987
988 // Location
989 updateAffineTransformation();
990
Michael Wright227c5542020-07-02 18:30:52 +0100991 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700992 // Compute pointer gesture detection parameters.
993 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +0800994 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700995
996 // Scale movements such that one whole swipe of the touch pad covers a
997 // given area relative to the diagonal size of the display when no acceleration
998 // is applied.
999 // Assume that the touch pad has a square aspect ratio such that movements in
1000 // X and Y of the same number of raw units cover the same physical distance.
1001 mPointerXMovementScale =
1002 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1003 mPointerYMovementScale = mPointerXMovementScale;
1004
1005 // Scale zooms to cover a smaller range of the display than movements do.
1006 // This value determines the area around the pointer that is affected by freeform
1007 // pointer gestures.
1008 mPointerXZoomScale =
1009 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1010 mPointerYZoomScale = mPointerXZoomScale;
1011
1012 // Max width between pointers to detect a swipe gesture is more than some fraction
1013 // of the diagonal axis of the touch pad. Touches that are wider than this are
1014 // translated into freeform gestures.
1015 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1016
1017 // Abort current pointer usages because the state has changed.
1018 abortPointerUsage(when, 0 /*policyFlags*/);
1019 }
1020
1021 // Inform the dispatcher about the changes.
1022 *outResetNeeded = true;
1023 bumpGeneration();
1024 }
1025}
1026
1027void TouchInputMapper::dumpSurface(std::string& dump) {
1028 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001029 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1030 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001031 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1032 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001033 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1034 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1036 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1037 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1038 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1039 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1040}
1041
1042void TouchInputMapper::configureVirtualKeys() {
1043 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001044 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001045
1046 mVirtualKeys.clear();
1047
1048 if (virtualKeyDefinitions.size() == 0) {
1049 return;
1050 }
1051
1052 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1053 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1054 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1055 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1056
1057 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1058 VirtualKey virtualKey;
1059
1060 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1061 int32_t keyCode;
1062 int32_t dummyKeyMetaState;
1063 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001064 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1065 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1067 continue; // drop the key
1068 }
1069
1070 virtualKey.keyCode = keyCode;
1071 virtualKey.flags = flags;
1072
1073 // convert the key definition's display coordinates into touch coordinates for a hit box
1074 int32_t halfWidth = virtualKeyDefinition.width / 2;
1075 int32_t halfHeight = virtualKeyDefinition.height / 2;
1076
1077 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001078 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001079 touchScreenLeft;
1080 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001081 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001083 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1084 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001085 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001086 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1087 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001088 touchScreenTop;
1089 mVirtualKeys.push_back(virtualKey);
1090 }
1091}
1092
1093void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1094 if (!mVirtualKeys.empty()) {
1095 dump += INDENT3 "Virtual Keys:\n";
1096
1097 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1098 const VirtualKey& virtualKey = mVirtualKeys[i];
1099 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1100 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1101 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1102 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1103 }
1104 }
1105}
1106
1107void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001108 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 Calibration& out = mCalibration;
1110
1111 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001112 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 String8 sizeCalibrationString;
1114 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1115 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001116 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001118 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001119 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001120 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001121 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001122 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001124 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001125 } else if (sizeCalibrationString != "default") {
1126 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1127 }
1128 }
1129
1130 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1131 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1132 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1133
1134 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001135 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 String8 pressureCalibrationString;
1137 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1138 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001139 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001140 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001141 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (pressureCalibrationString != "default") {
1145 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1146 pressureCalibrationString.string());
1147 }
1148 }
1149
1150 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1151
1152 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001153 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 String8 orientationCalibrationString;
1155 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1156 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001157 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001158 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001159 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001161 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001162 } else if (orientationCalibrationString != "default") {
1163 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1164 orientationCalibrationString.string());
1165 }
1166 }
1167
1168 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 String8 distanceCalibrationString;
1171 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1172 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (distanceCalibrationString != "default") {
1177 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1178 distanceCalibrationString.string());
1179 }
1180 }
1181
1182 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1183
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001185 String8 coverageCalibrationString;
1186 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1187 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (coverageCalibrationString != "default") {
1192 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1193 coverageCalibrationString.string());
1194 }
1195 }
1196}
1197
1198void TouchInputMapper::resolveCalibration() {
1199 // Size
1200 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001201 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1202 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 }
1204 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001205 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001206 }
1207
1208 // Pressure
1209 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001210 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1211 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 }
1213 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001214 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 }
1216
1217 // Orientation
1218 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001219 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1220 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 }
1222 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001223 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 }
1225
1226 // Distance
1227 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001228 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1229 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 }
1231 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001232 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 }
1234
1235 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001236 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1237 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 }
1239}
1240
1241void TouchInputMapper::dumpCalibration(std::string& dump) {
1242 dump += INDENT3 "Calibration:\n";
1243
1244 // Size
1245 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001246 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 dump += INDENT4 "touch.size.calibration: none\n";
1248 break;
Michael Wright227c5542020-07-02 18:30:52 +01001249 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 dump += INDENT4 "touch.size.calibration: geometric\n";
1251 break;
Michael Wright227c5542020-07-02 18:30:52 +01001252 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 dump += INDENT4 "touch.size.calibration: diameter\n";
1254 break;
Michael Wright227c5542020-07-02 18:30:52 +01001255 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256 dump += INDENT4 "touch.size.calibration: box\n";
1257 break;
Michael Wright227c5542020-07-02 18:30:52 +01001258 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 dump += INDENT4 "touch.size.calibration: area\n";
1260 break;
1261 default:
1262 ALOG_ASSERT(false);
1263 }
1264
1265 if (mCalibration.haveSizeScale) {
1266 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1267 }
1268
1269 if (mCalibration.haveSizeBias) {
1270 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1271 }
1272
1273 if (mCalibration.haveSizeIsSummed) {
1274 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1275 toString(mCalibration.sizeIsSummed));
1276 }
1277
1278 // Pressure
1279 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001280 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 dump += INDENT4 "touch.pressure.calibration: none\n";
1282 break;
Michael Wright227c5542020-07-02 18:30:52 +01001283 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 dump += INDENT4 "touch.pressure.calibration: physical\n";
1285 break;
Michael Wright227c5542020-07-02 18:30:52 +01001286 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1288 break;
1289 default:
1290 ALOG_ASSERT(false);
1291 }
1292
1293 if (mCalibration.havePressureScale) {
1294 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1295 }
1296
1297 // Orientation
1298 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001299 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 dump += INDENT4 "touch.orientation.calibration: none\n";
1301 break;
Michael Wright227c5542020-07-02 18:30:52 +01001302 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1304 break;
Michael Wright227c5542020-07-02 18:30:52 +01001305 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 dump += INDENT4 "touch.orientation.calibration: vector\n";
1307 break;
1308 default:
1309 ALOG_ASSERT(false);
1310 }
1311
1312 // Distance
1313 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001314 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.distance.calibration: none\n";
1316 break;
Michael Wright227c5542020-07-02 18:30:52 +01001317 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.distance.calibration: scaled\n";
1319 break;
1320 default:
1321 ALOG_ASSERT(false);
1322 }
1323
1324 if (mCalibration.haveDistanceScale) {
1325 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1326 }
1327
1328 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.coverage.calibration: none\n";
1331 break;
Michael Wright227c5542020-07-02 18:30:52 +01001332 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333 dump += INDENT4 "touch.coverage.calibration: box\n";
1334 break;
1335 default:
1336 ALOG_ASSERT(false);
1337 }
1338}
1339
1340void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1341 dump += INDENT3 "Affine Transformation:\n";
1342
1343 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1344 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1345 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1346 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1347 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1348 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1349}
1350
1351void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001352 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 mSurfaceOrientation);
1354}
1355
1356void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001357 mCursorButtonAccumulator.reset(getDeviceContext());
1358 mCursorScrollAccumulator.reset(getDeviceContext());
1359 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360
1361 mPointerVelocityControl.reset();
1362 mWheelXVelocityControl.reset();
1363 mWheelYVelocityControl.reset();
1364
1365 mRawStatesPending.clear();
1366 mCurrentRawState.clear();
1367 mCurrentCookedState.clear();
1368 mLastRawState.clear();
1369 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001370 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001371 mSentHoverEnter = false;
1372 mHavePointerIds = false;
1373 mCurrentMotionAborted = false;
1374 mDownTime = 0;
1375
1376 mCurrentVirtualKey.down = false;
1377
1378 mPointerGesture.reset();
1379 mPointerSimple.reset();
1380 resetExternalStylus();
1381
1382 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001383 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001384 mPointerController->clearSpots();
1385 }
1386
1387 InputMapper::reset(when);
1388}
1389
1390void TouchInputMapper::resetExternalStylus() {
1391 mExternalStylusState.clear();
1392 mExternalStylusId = -1;
1393 mExternalStylusFusionTimeout = LLONG_MAX;
1394 mExternalStylusDataPending = false;
1395}
1396
1397void TouchInputMapper::clearStylusDataPendingFlags() {
1398 mExternalStylusDataPending = false;
1399 mExternalStylusFusionTimeout = LLONG_MAX;
1400}
1401
1402void TouchInputMapper::process(const RawEvent* rawEvent) {
1403 mCursorButtonAccumulator.process(rawEvent);
1404 mCursorScrollAccumulator.process(rawEvent);
1405 mTouchButtonAccumulator.process(rawEvent);
1406
1407 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1408 sync(rawEvent->when);
1409 }
1410}
1411
1412void TouchInputMapper::sync(nsecs_t when) {
1413 const RawState* last =
1414 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1415
1416 // Push a new state.
1417 mRawStatesPending.emplace_back();
1418
1419 RawState* next = &mRawStatesPending.back();
1420 next->clear();
1421 next->when = when;
1422
1423 // Sync button state.
1424 next->buttonState =
1425 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1426
1427 // Sync scroll
1428 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1429 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1430 mCursorScrollAccumulator.finishSync();
1431
1432 // Sync touch
1433 syncTouch(when, next);
1434
1435 // Assign pointer ids.
1436 if (!mHavePointerIds) {
1437 assignPointerIds(last, next);
1438 }
1439
1440#if DEBUG_RAW_EVENTS
1441 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001442 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001443 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1444 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001445 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1446 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447#endif
1448
1449 processRawTouches(false /*timeout*/);
1450}
1451
1452void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001453 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001454 // Drop all input if the device is disabled.
Garfield Tanc734e4f2021-01-15 20:01:39 -08001455 cancelTouch(mCurrentRawState.when);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001456 mCurrentCookedState.clear();
1457 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001458 return;
1459 }
1460
1461 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1462 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1463 // touching the current state will only observe the events that have been dispatched to the
1464 // rest of the pipeline.
1465 const size_t N = mRawStatesPending.size();
1466 size_t count;
1467 for (count = 0; count < N; count++) {
1468 const RawState& next = mRawStatesPending[count];
1469
1470 // A failure to assign the stylus id means that we're waiting on stylus data
1471 // and so should defer the rest of the pipeline.
1472 if (assignExternalStylusId(next, timeout)) {
1473 break;
1474 }
1475
1476 // All ready to go.
1477 clearStylusDataPendingFlags();
1478 mCurrentRawState.copyFrom(next);
1479 if (mCurrentRawState.when < mLastRawState.when) {
1480 mCurrentRawState.when = mLastRawState.when;
1481 }
1482 cookAndDispatch(mCurrentRawState.when);
1483 }
1484 if (count != 0) {
1485 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1486 }
1487
1488 if (mExternalStylusDataPending) {
1489 if (timeout) {
1490 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1491 clearStylusDataPendingFlags();
1492 mCurrentRawState.copyFrom(mLastRawState);
1493#if DEBUG_STYLUS_FUSION
1494 ALOGD("Timeout expired, synthesizing event with new stylus data");
1495#endif
1496 cookAndDispatch(when);
1497 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1498 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1499 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1500 }
1501 }
1502}
1503
1504void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1505 // Always start with a clean state.
1506 mCurrentCookedState.clear();
1507
1508 // Apply stylus buttons to current raw state.
1509 applyExternalStylusButtonState(when);
1510
1511 // Handle policy on initial down or hover events.
1512 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1513 mCurrentRawState.rawPointerData.pointerCount != 0;
1514
1515 uint32_t policyFlags = 0;
1516 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1517 if (initialDown || buttonsPressed) {
1518 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001519 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001520 getContext()->fadePointer();
1521 }
1522
1523 if (mParameters.wake) {
1524 policyFlags |= POLICY_FLAG_WAKE;
1525 }
1526 }
1527
1528 // Consume raw off-screen touches before cooking pointer data.
1529 // If touches are consumed, subsequent code will not receive any pointer data.
1530 if (consumeRawTouches(when, policyFlags)) {
1531 mCurrentRawState.rawPointerData.clear();
1532 }
1533
1534 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1535 // with cooked pointer data that has the same ids and indices as the raw data.
1536 // The following code can use either the raw or cooked data, as needed.
1537 cookPointerData();
1538
1539 // Apply stylus pressure to current cooked state.
1540 applyExternalStylusTouchState(when);
1541
1542 // Synthesize key down from raw buttons if needed.
1543 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1544 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1545 mCurrentCookedState.buttonState);
1546
1547 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001548 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001549 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1550 uint32_t id = idBits.clearFirstMarkedBit();
1551 const RawPointerData::Pointer& pointer =
1552 mCurrentRawState.rawPointerData.pointerForId(id);
1553 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1554 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1555 mCurrentCookedState.stylusIdBits.markBit(id);
1556 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1557 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1558 mCurrentCookedState.fingerIdBits.markBit(id);
1559 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1560 mCurrentCookedState.mouseIdBits.markBit(id);
1561 }
1562 }
1563 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1564 uint32_t id = idBits.clearFirstMarkedBit();
1565 const RawPointerData::Pointer& pointer =
1566 mCurrentRawState.rawPointerData.pointerForId(id);
1567 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1568 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1569 mCurrentCookedState.stylusIdBits.markBit(id);
1570 }
1571 }
1572
1573 // Stylus takes precedence over all tools, then mouse, then finger.
1574 PointerUsage pointerUsage = mPointerUsage;
1575 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1576 mCurrentCookedState.mouseIdBits.clear();
1577 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001578 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1580 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001581 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001582 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1583 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001584 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001585 }
1586
1587 dispatchPointerUsage(when, policyFlags, pointerUsage);
1588 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001589 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590
1591 if (!mCurrentMotionAborted) {
1592 dispatchButtonRelease(when, policyFlags);
1593 dispatchHoverExit(when, policyFlags);
1594 dispatchTouches(when, policyFlags);
1595 dispatchHoverEnterAndMove(when, policyFlags);
1596 dispatchButtonPress(when, policyFlags);
1597 }
1598
1599 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1600 mCurrentMotionAborted = false;
1601 }
1602 }
1603
1604 // Synthesize key up from raw buttons if needed.
1605 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1606 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1607 mCurrentCookedState.buttonState);
1608
1609 // Clear some transient state.
1610 mCurrentRawState.rawVScroll = 0;
1611 mCurrentRawState.rawHScroll = 0;
1612
1613 // Copy current touch to last touch in preparation for the next cycle.
1614 mLastRawState.copyFrom(mCurrentRawState);
1615 mLastCookedState.copyFrom(mCurrentCookedState);
1616}
1617
Garfield Tanc734e4f2021-01-15 20:01:39 -08001618void TouchInputMapper::updateTouchSpots() {
1619 if (!mConfig.showTouches || mPointerController == nullptr) {
1620 return;
1621 }
1622
1623 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1624 // clear touch spots.
1625 if (mDeviceMode != DeviceMode::DIRECT &&
1626 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1627 return;
1628 }
1629
1630 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1631 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1632
1633 mPointerController->setButtonState(mCurrentRawState.buttonState);
1634 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1635 mCurrentCookedState.cookedPointerData.idToIndex,
1636 mCurrentCookedState.cookedPointerData.touchingIdBits,
1637 mViewport.displayId);
1638}
1639
1640bool TouchInputMapper::isTouchScreen() {
1641 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1642 mParameters.hasAssociatedDisplay;
1643}
1644
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001645void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001646 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1648 }
1649}
1650
1651void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1652 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1653 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1654
1655 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1656 float pressure = mExternalStylusState.pressure;
1657 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1658 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1659 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1660 }
1661 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1662 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1663
1664 PointerProperties& properties =
1665 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1666 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1667 properties.toolType = mExternalStylusState.toolType;
1668 }
1669 }
1670}
1671
1672bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001673 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001674 return false;
1675 }
1676
1677 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1678 state.rawPointerData.pointerCount != 0;
1679 if (initialDown) {
1680 if (mExternalStylusState.pressure != 0.0f) {
1681#if DEBUG_STYLUS_FUSION
1682 ALOGD("Have both stylus and touch data, beginning fusion");
1683#endif
1684 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1685 } else if (timeout) {
1686#if DEBUG_STYLUS_FUSION
1687 ALOGD("Timeout expired, assuming touch is not a stylus.");
1688#endif
1689 resetExternalStylus();
1690 } else {
1691 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1692 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1693 }
1694#if DEBUG_STYLUS_FUSION
1695 ALOGD("No stylus data but stylus is connected, requesting timeout "
1696 "(%" PRId64 "ms)",
1697 mExternalStylusFusionTimeout);
1698#endif
1699 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1700 return true;
1701 }
1702 }
1703
1704 // Check if the stylus pointer has gone up.
1705 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1706#if DEBUG_STYLUS_FUSION
1707 ALOGD("Stylus pointer is going up");
1708#endif
1709 mExternalStylusId = -1;
1710 }
1711
1712 return false;
1713}
1714
1715void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001716 if (mDeviceMode == DeviceMode::POINTER) {
1717 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001718 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1719 }
Michael Wright227c5542020-07-02 18:30:52 +01001720 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001721 if (mExternalStylusFusionTimeout < when) {
1722 processRawTouches(true /*timeout*/);
1723 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1724 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1725 }
1726 }
1727}
1728
1729void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1730 mExternalStylusState.copyFrom(state);
1731 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1732 // We're either in the middle of a fused stream of data or we're waiting on data before
1733 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1734 // data.
1735 mExternalStylusDataPending = true;
1736 processRawTouches(false /*timeout*/);
1737 }
1738}
1739
1740bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1741 // Check for release of a virtual key.
1742 if (mCurrentVirtualKey.down) {
1743 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1744 // Pointer went up while virtual key was down.
1745 mCurrentVirtualKey.down = false;
1746 if (!mCurrentVirtualKey.ignored) {
1747#if DEBUG_VIRTUAL_KEYS
1748 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1749 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1750#endif
1751 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1752 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1753 }
1754 return true;
1755 }
1756
1757 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1758 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1759 const RawPointerData::Pointer& pointer =
1760 mCurrentRawState.rawPointerData.pointerForId(id);
1761 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1762 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1763 // Pointer is still within the space of the virtual key.
1764 return true;
1765 }
1766 }
1767
1768 // Pointer left virtual key area or another pointer also went down.
1769 // Send key cancellation but do not consume the touch yet.
1770 // This is useful when the user swipes through from the virtual key area
1771 // into the main display surface.
1772 mCurrentVirtualKey.down = false;
1773 if (!mCurrentVirtualKey.ignored) {
1774#if DEBUG_VIRTUAL_KEYS
1775 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1776 mCurrentVirtualKey.scanCode);
1777#endif
1778 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1779 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1780 AKEY_EVENT_FLAG_CANCELED);
1781 }
1782 }
1783
1784 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1785 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1786 // Pointer just went down. Check for virtual key press or off-screen touches.
1787 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1788 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001789 // Exclude unscaled device for inside surface checking.
1790 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001791 // If exactly one pointer went down, check for virtual key hit.
1792 // Otherwise we will drop the entire stroke.
1793 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1794 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1795 if (virtualKey) {
1796 mCurrentVirtualKey.down = true;
1797 mCurrentVirtualKey.downTime = when;
1798 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1799 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1800 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001801 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1802 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001803
1804 if (!mCurrentVirtualKey.ignored) {
1805#if DEBUG_VIRTUAL_KEYS
1806 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1807 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1808#endif
1809 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1810 AKEY_EVENT_FLAG_FROM_SYSTEM |
1811 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1812 }
1813 }
1814 }
1815 return true;
1816 }
1817 }
1818
1819 // Disable all virtual key touches that happen within a short time interval of the
1820 // most recent touch within the screen area. The idea is to filter out stray
1821 // virtual key presses when interacting with the touch screen.
1822 //
1823 // Problems we're trying to solve:
1824 //
1825 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1826 // virtual key area that is implemented by a separate touch panel and accidentally
1827 // triggers a virtual key.
1828 //
1829 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1830 // area and accidentally triggers a virtual key. This often happens when virtual keys
1831 // are layed out below the screen near to where the on screen keyboard's space bar
1832 // is displayed.
1833 if (mConfig.virtualKeyQuietTime > 0 &&
1834 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001835 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001836 }
1837 return false;
1838}
1839
1840void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1841 int32_t keyEventAction, int32_t keyEventFlags) {
1842 int32_t keyCode = mCurrentVirtualKey.keyCode;
1843 int32_t scanCode = mCurrentVirtualKey.scanCode;
1844 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001845 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846 policyFlags |= POLICY_FLAG_VIRTUAL;
1847
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06001848 getContext()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
1849 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode,
1850 metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001851}
1852
1853void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1854 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1855 if (!currentIdBits.isEmpty()) {
1856 int32_t metaState = getContext()->getGlobalMetaState();
1857 int32_t buttonState = mCurrentCookedState.buttonState;
1858 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1859 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1860 mCurrentCookedState.cookedPointerData.pointerProperties,
1861 mCurrentCookedState.cookedPointerData.pointerCoords,
1862 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1863 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1864 mCurrentMotionAborted = true;
1865 }
1866}
1867
1868void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1869 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1870 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1871 int32_t metaState = getContext()->getGlobalMetaState();
1872 int32_t buttonState = mCurrentCookedState.buttonState;
1873
1874 if (currentIdBits == lastIdBits) {
1875 if (!currentIdBits.isEmpty()) {
1876 // No pointer id changes so this is a move event.
1877 // The listener takes care of batching moves so we don't have to deal with that here.
1878 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1879 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1880 mCurrentCookedState.cookedPointerData.pointerProperties,
1881 mCurrentCookedState.cookedPointerData.pointerCoords,
1882 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1883 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1884 }
1885 } else {
1886 // There may be pointers going up and pointers going down and pointers moving
1887 // all at the same time.
1888 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1889 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1890 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1891 BitSet32 dispatchedIdBits(lastIdBits.value);
1892
1893 // Update last coordinates of pointers that have moved so that we observe the new
1894 // pointer positions at the same time as other pointers that have just gone up.
1895 bool moveNeeded =
1896 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1897 mCurrentCookedState.cookedPointerData.pointerCoords,
1898 mCurrentCookedState.cookedPointerData.idToIndex,
1899 mLastCookedState.cookedPointerData.pointerProperties,
1900 mLastCookedState.cookedPointerData.pointerCoords,
1901 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1902 if (buttonState != mLastCookedState.buttonState) {
1903 moveNeeded = true;
1904 }
1905
1906 // Dispatch pointer up events.
1907 while (!upIdBits.isEmpty()) {
1908 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001909 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001910 if (isCanceled) {
1911 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1912 }
arthurhungcc7f9802020-04-30 17:55:40 +08001913 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1914 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001915 mLastCookedState.cookedPointerData.pointerProperties,
1916 mLastCookedState.cookedPointerData.pointerCoords,
1917 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1918 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1919 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001920 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921 }
1922
1923 // Dispatch move events if any of the remaining pointers moved from their old locations.
1924 // Although applications receive new locations as part of individual pointer up
1925 // events, they do not generally handle them except when presented in a move event.
1926 if (moveNeeded && !moveIdBits.isEmpty()) {
1927 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1928 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1929 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1930 mCurrentCookedState.cookedPointerData.pointerCoords,
1931 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1932 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1933 }
1934
1935 // Dispatch pointer down events using the new pointer locations.
1936 while (!downIdBits.isEmpty()) {
1937 uint32_t downId = downIdBits.clearFirstMarkedBit();
1938 dispatchedIdBits.markBit(downId);
1939
1940 if (dispatchedIdBits.count() == 1) {
1941 // First pointer is going down. Set down time.
1942 mDownTime = when;
1943 }
1944
1945 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1946 metaState, buttonState, 0,
1947 mCurrentCookedState.cookedPointerData.pointerProperties,
1948 mCurrentCookedState.cookedPointerData.pointerCoords,
1949 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1950 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1951 }
1952 }
1953}
1954
1955void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1956 if (mSentHoverEnter &&
1957 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1958 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1959 int32_t metaState = getContext()->getGlobalMetaState();
1960 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1961 mLastCookedState.buttonState, 0,
1962 mLastCookedState.cookedPointerData.pointerProperties,
1963 mLastCookedState.cookedPointerData.pointerCoords,
1964 mLastCookedState.cookedPointerData.idToIndex,
1965 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1966 mOrientedYPrecision, mDownTime);
1967 mSentHoverEnter = false;
1968 }
1969}
1970
1971void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1972 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1973 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1974 int32_t metaState = getContext()->getGlobalMetaState();
1975 if (!mSentHoverEnter) {
1976 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1977 metaState, mCurrentRawState.buttonState, 0,
1978 mCurrentCookedState.cookedPointerData.pointerProperties,
1979 mCurrentCookedState.cookedPointerData.pointerCoords,
1980 mCurrentCookedState.cookedPointerData.idToIndex,
1981 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1982 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1983 mSentHoverEnter = true;
1984 }
1985
1986 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1987 mCurrentRawState.buttonState, 0,
1988 mCurrentCookedState.cookedPointerData.pointerProperties,
1989 mCurrentCookedState.cookedPointerData.pointerCoords,
1990 mCurrentCookedState.cookedPointerData.idToIndex,
1991 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1992 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1993 }
1994}
1995
1996void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1997 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1998 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1999 const int32_t metaState = getContext()->getGlobalMetaState();
2000 int32_t buttonState = mLastCookedState.buttonState;
2001 while (!releasedButtons.isEmpty()) {
2002 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2003 buttonState &= ~actionButton;
2004 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2005 actionButton, 0, metaState, buttonState, 0,
2006 mCurrentCookedState.cookedPointerData.pointerProperties,
2007 mCurrentCookedState.cookedPointerData.pointerCoords,
2008 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2009 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2010 }
2011}
2012
2013void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2014 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2015 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2016 const int32_t metaState = getContext()->getGlobalMetaState();
2017 int32_t buttonState = mLastCookedState.buttonState;
2018 while (!pressedButtons.isEmpty()) {
2019 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2020 buttonState |= actionButton;
2021 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2022 0, metaState, buttonState, 0,
2023 mCurrentCookedState.cookedPointerData.pointerProperties,
2024 mCurrentCookedState.cookedPointerData.pointerCoords,
2025 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2026 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2027 }
2028}
2029
2030const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2031 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2032 return cookedPointerData.touchingIdBits;
2033 }
2034 return cookedPointerData.hoveringIdBits;
2035}
2036
2037void TouchInputMapper::cookPointerData() {
2038 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2039
2040 mCurrentCookedState.cookedPointerData.clear();
2041 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2042 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2043 mCurrentRawState.rawPointerData.hoveringIdBits;
2044 mCurrentCookedState.cookedPointerData.touchingIdBits =
2045 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002046 mCurrentCookedState.cookedPointerData.canceledIdBits =
2047 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002048
2049 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2050 mCurrentCookedState.buttonState = 0;
2051 } else {
2052 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2053 }
2054
2055 // Walk through the the active pointers and map device coordinates onto
2056 // surface coordinates and adjust for display orientation.
2057 for (uint32_t i = 0; i < currentPointerCount; i++) {
2058 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2059
2060 // Size
2061 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2062 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002063 case Calibration::SizeCalibration::GEOMETRIC:
2064 case Calibration::SizeCalibration::DIAMETER:
2065 case Calibration::SizeCalibration::BOX:
2066 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002067 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2068 touchMajor = in.touchMajor;
2069 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2070 toolMajor = in.toolMajor;
2071 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2072 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2073 : in.touchMajor;
2074 } else if (mRawPointerAxes.touchMajor.valid) {
2075 toolMajor = touchMajor = in.touchMajor;
2076 toolMinor = touchMinor =
2077 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2078 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2079 : in.touchMajor;
2080 } else if (mRawPointerAxes.toolMajor.valid) {
2081 touchMajor = toolMajor = in.toolMajor;
2082 touchMinor = toolMinor =
2083 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2084 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2085 : in.toolMajor;
2086 } else {
2087 ALOG_ASSERT(false,
2088 "No touch or tool axes. "
2089 "Size calibration should have been resolved to NONE.");
2090 touchMajor = 0;
2091 touchMinor = 0;
2092 toolMajor = 0;
2093 toolMinor = 0;
2094 size = 0;
2095 }
2096
2097 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2098 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2099 if (touchingCount > 1) {
2100 touchMajor /= touchingCount;
2101 touchMinor /= touchingCount;
2102 toolMajor /= touchingCount;
2103 toolMinor /= touchingCount;
2104 size /= touchingCount;
2105 }
2106 }
2107
Michael Wright227c5542020-07-02 18:30:52 +01002108 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002109 touchMajor *= mGeometricScale;
2110 touchMinor *= mGeometricScale;
2111 toolMajor *= mGeometricScale;
2112 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002113 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002114 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2115 touchMinor = touchMajor;
2116 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2117 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002118 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002119 touchMinor = touchMajor;
2120 toolMinor = toolMajor;
2121 }
2122
2123 mCalibration.applySizeScaleAndBias(&touchMajor);
2124 mCalibration.applySizeScaleAndBias(&touchMinor);
2125 mCalibration.applySizeScaleAndBias(&toolMajor);
2126 mCalibration.applySizeScaleAndBias(&toolMinor);
2127 size *= mSizeScale;
2128 break;
2129 default:
2130 touchMajor = 0;
2131 touchMinor = 0;
2132 toolMajor = 0;
2133 toolMinor = 0;
2134 size = 0;
2135 break;
2136 }
2137
2138 // Pressure
2139 float pressure;
2140 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002141 case Calibration::PressureCalibration::PHYSICAL:
2142 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002143 pressure = in.pressure * mPressureScale;
2144 break;
2145 default:
2146 pressure = in.isHovering ? 0 : 1;
2147 break;
2148 }
2149
2150 // Tilt and Orientation
2151 float tilt;
2152 float orientation;
2153 if (mHaveTilt) {
2154 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2155 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2156 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2157 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2158 } else {
2159 tilt = 0;
2160
2161 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002162 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163 orientation = in.orientation * mOrientationScale;
2164 break;
Michael Wright227c5542020-07-02 18:30:52 +01002165 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002166 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2167 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2168 if (c1 != 0 || c2 != 0) {
2169 orientation = atan2f(c1, c2) * 0.5f;
2170 float confidence = hypotf(c1, c2);
2171 float scale = 1.0f + confidence / 16.0f;
2172 touchMajor *= scale;
2173 touchMinor /= scale;
2174 toolMajor *= scale;
2175 toolMinor /= scale;
2176 } else {
2177 orientation = 0;
2178 }
2179 break;
2180 }
2181 default:
2182 orientation = 0;
2183 }
2184 }
2185
2186 // Distance
2187 float distance;
2188 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002189 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002190 distance = in.distance * mDistanceScale;
2191 break;
2192 default:
2193 distance = 0;
2194 }
2195
2196 // Coverage
2197 int32_t rawLeft, rawTop, rawRight, rawBottom;
2198 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002199 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002200 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2201 rawRight = in.toolMinor & 0x0000ffff;
2202 rawBottom = in.toolMajor & 0x0000ffff;
2203 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2204 break;
2205 default:
2206 rawLeft = rawTop = rawRight = rawBottom = 0;
2207 break;
2208 }
2209
2210 // Adjust X,Y coords for device calibration
2211 // TODO: Adjust coverage coords?
2212 float xTransformed = in.x, yTransformed = in.y;
2213 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002214 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002215
2216 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002217 float left, top, right, bottom;
2218
2219 switch (mSurfaceOrientation) {
2220 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002221 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2222 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2223 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2224 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2225 orientation -= M_PI_2;
2226 if (mOrientedRanges.haveOrientation &&
2227 orientation < mOrientedRanges.orientation.min) {
2228 orientation +=
2229 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2230 }
2231 break;
2232 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002233 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2234 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2235 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2236 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2237 orientation -= M_PI;
2238 if (mOrientedRanges.haveOrientation &&
2239 orientation < mOrientedRanges.orientation.min) {
2240 orientation +=
2241 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2242 }
2243 break;
2244 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002245 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2246 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2247 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2248 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2249 orientation += M_PI_2;
2250 if (mOrientedRanges.haveOrientation &&
2251 orientation > mOrientedRanges.orientation.max) {
2252 orientation -=
2253 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2254 }
2255 break;
2256 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002257 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2258 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2259 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2260 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2261 break;
2262 }
2263
2264 // Write output coords.
2265 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2266 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002267 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2268 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002269 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2270 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2271 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2272 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2273 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2274 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2275 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002276 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002277 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2278 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2279 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2280 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2281 } else {
2282 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2283 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2284 }
2285
Chris Ye364fdb52020-08-05 15:07:56 -07002286 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002287 uint32_t id = in.id;
2288 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2289 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2290 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2291 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2292 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2293 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2294 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2295 }
2296
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 // Write output properties.
2298 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002299 properties.clear();
2300 properties.id = id;
2301 properties.toolType = in.toolType;
2302
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002303 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002304 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002305 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002306 }
2307}
2308
2309void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2310 PointerUsage pointerUsage) {
2311 if (pointerUsage != mPointerUsage) {
2312 abortPointerUsage(when, policyFlags);
2313 mPointerUsage = pointerUsage;
2314 }
2315
2316 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002317 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002318 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2319 break;
Michael Wright227c5542020-07-02 18:30:52 +01002320 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002321 dispatchPointerStylus(when, policyFlags);
2322 break;
Michael Wright227c5542020-07-02 18:30:52 +01002323 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002324 dispatchPointerMouse(when, policyFlags);
2325 break;
Michael Wright227c5542020-07-02 18:30:52 +01002326 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002327 break;
2328 }
2329}
2330
2331void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2332 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002333 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002334 abortPointerGestures(when, policyFlags);
2335 break;
Michael Wright227c5542020-07-02 18:30:52 +01002336 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002337 abortPointerStylus(when, policyFlags);
2338 break;
Michael Wright227c5542020-07-02 18:30:52 +01002339 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002340 abortPointerMouse(when, policyFlags);
2341 break;
Michael Wright227c5542020-07-02 18:30:52 +01002342 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 break;
2344 }
2345
Michael Wright227c5542020-07-02 18:30:52 +01002346 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347}
2348
2349void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2350 // Update current gesture coordinates.
2351 bool cancelPreviousGesture, finishPreviousGesture;
2352 bool sendEvents =
2353 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2354 if (!sendEvents) {
2355 return;
2356 }
2357 if (finishPreviousGesture) {
2358 cancelPreviousGesture = false;
2359 }
2360
2361 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002362 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002363 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002364 if (finishPreviousGesture || cancelPreviousGesture) {
2365 mPointerController->clearSpots();
2366 }
2367
Michael Wright227c5542020-07-02 18:30:52 +01002368 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2370 mPointerGesture.currentGestureIdToIndex,
2371 mPointerGesture.currentGestureIdBits,
2372 mPointerController->getDisplayId());
2373 }
2374 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002375 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002376 }
2377
2378 // Show or hide the pointer if needed.
2379 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002380 case PointerGesture::Mode::NEUTRAL:
2381 case PointerGesture::Mode::QUIET:
2382 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2383 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002385 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002386 }
2387 break;
Michael Wright227c5542020-07-02 18:30:52 +01002388 case PointerGesture::Mode::TAP:
2389 case PointerGesture::Mode::TAP_DRAG:
2390 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2391 case PointerGesture::Mode::HOVER:
2392 case PointerGesture::Mode::PRESS:
2393 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 // Unfade the pointer when the current gesture manipulates the
2395 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002396 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 break;
Michael Wright227c5542020-07-02 18:30:52 +01002398 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002399 // Fade the pointer when the current gesture manipulates a different
2400 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002401 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002402 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002404 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 }
2406 break;
2407 }
2408
2409 // Send events!
2410 int32_t metaState = getContext()->getGlobalMetaState();
2411 int32_t buttonState = mCurrentCookedState.buttonState;
2412
2413 // Update last coordinates of pointers that have moved so that we observe the new
2414 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002415 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2416 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2417 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2418 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2419 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2420 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002421 bool moveNeeded = false;
2422 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2423 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2424 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2425 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2426 mPointerGesture.lastGestureIdBits.value);
2427 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2428 mPointerGesture.currentGestureCoords,
2429 mPointerGesture.currentGestureIdToIndex,
2430 mPointerGesture.lastGestureProperties,
2431 mPointerGesture.lastGestureCoords,
2432 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2433 if (buttonState != mLastCookedState.buttonState) {
2434 moveNeeded = true;
2435 }
2436 }
2437
2438 // Send motion events for all pointers that went up or were canceled.
2439 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2440 if (!dispatchedGestureIdBits.isEmpty()) {
2441 if (cancelPreviousGesture) {
2442 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2443 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2444 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2445 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2446 mPointerGesture.downTime);
2447
2448 dispatchedGestureIdBits.clear();
2449 } else {
2450 BitSet32 upGestureIdBits;
2451 if (finishPreviousGesture) {
2452 upGestureIdBits = dispatchedGestureIdBits;
2453 } else {
2454 upGestureIdBits.value =
2455 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2456 }
2457 while (!upGestureIdBits.isEmpty()) {
2458 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2459
2460 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2461 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2462 mPointerGesture.lastGestureProperties,
2463 mPointerGesture.lastGestureCoords,
2464 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2465 0, mPointerGesture.downTime);
2466
2467 dispatchedGestureIdBits.clearBit(id);
2468 }
2469 }
2470 }
2471
2472 // Send motion events for all pointers that moved.
2473 if (moveNeeded) {
2474 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2475 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2476 mPointerGesture.currentGestureProperties,
2477 mPointerGesture.currentGestureCoords,
2478 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2479 mPointerGesture.downTime);
2480 }
2481
2482 // Send motion events for all pointers that went down.
2483 if (down) {
2484 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2485 ~dispatchedGestureIdBits.value);
2486 while (!downGestureIdBits.isEmpty()) {
2487 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2488 dispatchedGestureIdBits.markBit(id);
2489
2490 if (dispatchedGestureIdBits.count() == 1) {
2491 mPointerGesture.downTime = when;
2492 }
2493
2494 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2495 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2496 mPointerGesture.currentGestureCoords,
2497 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2498 0, mPointerGesture.downTime);
2499 }
2500 }
2501
2502 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002503 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2505 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2506 mPointerGesture.currentGestureProperties,
2507 mPointerGesture.currentGestureCoords,
2508 mPointerGesture.currentGestureIdToIndex,
2509 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2510 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2511 // Synthesize a hover move event after all pointers go up to indicate that
2512 // the pointer is hovering again even if the user is not currently touching
2513 // the touch pad. This ensures that a view will receive a fresh hover enter
2514 // event after a tap.
2515 float x, y;
2516 mPointerController->getPosition(&x, &y);
2517
2518 PointerProperties pointerProperties;
2519 pointerProperties.clear();
2520 pointerProperties.id = 0;
2521 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2522
2523 PointerCoords pointerCoords;
2524 pointerCoords.clear();
2525 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2526 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2527
2528 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06002529 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
2530 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState,
2531 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
2532 &pointerProperties, &pointerCoords, 0, 0, x, y,
2533 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 }
2535
2536 // Update state.
2537 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2538 if (!down) {
2539 mPointerGesture.lastGestureIdBits.clear();
2540 } else {
2541 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2542 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2543 uint32_t id = idBits.clearFirstMarkedBit();
2544 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2545 mPointerGesture.lastGestureProperties[index].copyFrom(
2546 mPointerGesture.currentGestureProperties[index]);
2547 mPointerGesture.lastGestureCoords[index].copyFrom(
2548 mPointerGesture.currentGestureCoords[index]);
2549 mPointerGesture.lastGestureIdToIndex[id] = index;
2550 }
2551 }
2552}
2553
2554void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2555 // Cancel previously dispatches pointers.
2556 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2557 int32_t metaState = getContext()->getGlobalMetaState();
2558 int32_t buttonState = mCurrentRawState.buttonState;
2559 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2560 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2561 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2562 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2563 0, 0, mPointerGesture.downTime);
2564 }
2565
2566 // Reset the current pointer gesture.
2567 mPointerGesture.reset();
2568 mPointerVelocityControl.reset();
2569
2570 // Remove any current spots.
2571 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002572 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002573 mPointerController->clearSpots();
2574 }
2575}
2576
2577bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2578 bool* outFinishPreviousGesture, bool isTimeout) {
2579 *outCancelPreviousGesture = false;
2580 *outFinishPreviousGesture = false;
2581
2582 // Handle TAP timeout.
2583 if (isTimeout) {
2584#if DEBUG_GESTURES
2585 ALOGD("Gestures: Processing timeout");
2586#endif
2587
Michael Wright227c5542020-07-02 18:30:52 +01002588 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002589 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2590 // The tap/drag timeout has not yet expired.
2591 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2592 mConfig.pointerGestureTapDragInterval);
2593 } else {
2594 // The tap is finished.
2595#if DEBUG_GESTURES
2596 ALOGD("Gestures: TAP finished");
2597#endif
2598 *outFinishPreviousGesture = true;
2599
2600 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002601 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002602 mPointerGesture.currentGestureIdBits.clear();
2603
2604 mPointerVelocityControl.reset();
2605 return true;
2606 }
2607 }
2608
2609 // We did not handle this timeout.
2610 return false;
2611 }
2612
2613 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2614 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2615
2616 // Update the velocity tracker.
2617 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002618 std::vector<VelocityTracker::Position> positions;
2619 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002620 uint32_t id = idBits.clearFirstMarkedBit();
2621 const RawPointerData::Pointer& pointer =
2622 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002623 float x = pointer.x * mPointerXMovementScale;
2624 float y = pointer.y * mPointerYMovementScale;
2625 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002626 }
2627 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2628 positions);
2629 }
2630
2631 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2632 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002633 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2634 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2635 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002636 mPointerGesture.resetTap();
2637 }
2638
2639 // Pick a new active touch id if needed.
2640 // Choose an arbitrary pointer that just went down, if there is one.
2641 // Otherwise choose an arbitrary remaining pointer.
2642 // This guarantees we always have an active touch id when there is at least one pointer.
2643 // We keep the same active touch id for as long as possible.
2644 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2645 int32_t activeTouchId = lastActiveTouchId;
2646 if (activeTouchId < 0) {
2647 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2648 activeTouchId = mPointerGesture.activeTouchId =
2649 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2650 mPointerGesture.firstTouchTime = when;
2651 }
2652 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2653 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2654 activeTouchId = mPointerGesture.activeTouchId =
2655 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2656 } else {
2657 activeTouchId = mPointerGesture.activeTouchId = -1;
2658 }
2659 }
2660
2661 // Determine whether we are in quiet time.
2662 bool isQuietTime = false;
2663 if (activeTouchId < 0) {
2664 mPointerGesture.resetQuietTime();
2665 } else {
2666 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2667 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002668 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2669 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2670 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002671 currentFingerCount < 2) {
2672 // Enter quiet time when exiting swipe or freeform state.
2673 // This is to prevent accidentally entering the hover state and flinging the
2674 // pointer when finishing a swipe and there is still one pointer left onscreen.
2675 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002676 } else if (mPointerGesture.lastGestureMode ==
2677 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002678 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2679 // Enter quiet time when releasing the button and there are still two or more
2680 // fingers down. This may indicate that one finger was used to press the button
2681 // but it has not gone up yet.
2682 isQuietTime = true;
2683 }
2684 if (isQuietTime) {
2685 mPointerGesture.quietTime = when;
2686 }
2687 }
2688 }
2689
2690 // Switch states based on button and pointer state.
2691 if (isQuietTime) {
2692 // Case 1: Quiet time. (QUIET)
2693#if DEBUG_GESTURES
2694 ALOGD("Gestures: QUIET for next %0.3fms",
2695 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2696#endif
Michael Wright227c5542020-07-02 18:30:52 +01002697 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002698 *outFinishPreviousGesture = true;
2699 }
2700
2701 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002702 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002703 mPointerGesture.currentGestureIdBits.clear();
2704
2705 mPointerVelocityControl.reset();
2706 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2707 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2708 // The pointer follows the active touch point.
2709 // Emit DOWN, MOVE, UP events at the pointer location.
2710 //
2711 // Only the active touch matters; other fingers are ignored. This policy helps
2712 // to handle the case where the user places a second finger on the touch pad
2713 // to apply the necessary force to depress an integrated button below the surface.
2714 // We don't want the second finger to be delivered to applications.
2715 //
2716 // For this to work well, we need to make sure to track the pointer that is really
2717 // active. If the user first puts one finger down to click then adds another
2718 // finger to drag then the active pointer should switch to the finger that is
2719 // being dragged.
2720#if DEBUG_GESTURES
2721 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2722 "currentFingerCount=%d",
2723 activeTouchId, currentFingerCount);
2724#endif
2725 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002726 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002727 *outFinishPreviousGesture = true;
2728 mPointerGesture.activeGestureId = 0;
2729 }
2730
2731 // Switch pointers if needed.
2732 // Find the fastest pointer and follow it.
2733 if (activeTouchId >= 0 && currentFingerCount > 1) {
2734 int32_t bestId = -1;
2735 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2736 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2737 uint32_t id = idBits.clearFirstMarkedBit();
2738 float vx, vy;
2739 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2740 float speed = hypotf(vx, vy);
2741 if (speed > bestSpeed) {
2742 bestId = id;
2743 bestSpeed = speed;
2744 }
2745 }
2746 }
2747 if (bestId >= 0 && bestId != activeTouchId) {
2748 mPointerGesture.activeTouchId = activeTouchId = bestId;
2749#if DEBUG_GESTURES
2750 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2751 "bestId=%d, bestSpeed=%0.3f",
2752 bestId, bestSpeed);
2753#endif
2754 }
2755 }
2756
2757 float deltaX = 0, deltaY = 0;
2758 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2759 const RawPointerData::Pointer& currentPointer =
2760 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2761 const RawPointerData::Pointer& lastPointer =
2762 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2763 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2764 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2765
2766 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2767 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2768
2769 // Move the pointer using a relative motion.
2770 // When using spots, the click will occur at the position of the anchor
2771 // spot and all other spots will move there.
2772 mPointerController->move(deltaX, deltaY);
2773 } else {
2774 mPointerVelocityControl.reset();
2775 }
2776
2777 float x, y;
2778 mPointerController->getPosition(&x, &y);
2779
Michael Wright227c5542020-07-02 18:30:52 +01002780 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002781 mPointerGesture.currentGestureIdBits.clear();
2782 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2783 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2784 mPointerGesture.currentGestureProperties[0].clear();
2785 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2786 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2787 mPointerGesture.currentGestureCoords[0].clear();
2788 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2789 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2790 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2791 } else if (currentFingerCount == 0) {
2792 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002793 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 *outFinishPreviousGesture = true;
2795 }
2796
2797 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2798 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2799 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002800 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2801 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002802 lastFingerCount == 1) {
2803 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2804 float x, y;
2805 mPointerController->getPosition(&x, &y);
2806 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2807 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2808#if DEBUG_GESTURES
2809 ALOGD("Gestures: TAP");
2810#endif
2811
2812 mPointerGesture.tapUpTime = when;
2813 getContext()->requestTimeoutAtTime(when +
2814 mConfig.pointerGestureTapDragInterval);
2815
2816 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002817 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002818 mPointerGesture.currentGestureIdBits.clear();
2819 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2820 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2821 mPointerGesture.currentGestureProperties[0].clear();
2822 mPointerGesture.currentGestureProperties[0].id =
2823 mPointerGesture.activeGestureId;
2824 mPointerGesture.currentGestureProperties[0].toolType =
2825 AMOTION_EVENT_TOOL_TYPE_FINGER;
2826 mPointerGesture.currentGestureCoords[0].clear();
2827 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2828 mPointerGesture.tapX);
2829 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2830 mPointerGesture.tapY);
2831 mPointerGesture.currentGestureCoords[0]
2832 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2833
2834 tapped = true;
2835 } else {
2836#if DEBUG_GESTURES
2837 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2838 y - mPointerGesture.tapY);
2839#endif
2840 }
2841 } else {
2842#if DEBUG_GESTURES
2843 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2844 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2845 (when - mPointerGesture.tapDownTime) * 0.000001f);
2846 } else {
2847 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2848 }
2849#endif
2850 }
2851 }
2852
2853 mPointerVelocityControl.reset();
2854
2855 if (!tapped) {
2856#if DEBUG_GESTURES
2857 ALOGD("Gestures: NEUTRAL");
2858#endif
2859 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002860 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002861 mPointerGesture.currentGestureIdBits.clear();
2862 }
2863 } else if (currentFingerCount == 1) {
2864 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2865 // The pointer follows the active touch point.
2866 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2867 // When in TAP_DRAG, emit MOVE events at the pointer location.
2868 ALOG_ASSERT(activeTouchId >= 0);
2869
Michael Wright227c5542020-07-02 18:30:52 +01002870 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2871 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2873 float x, y;
2874 mPointerController->getPosition(&x, &y);
2875 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2876 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002877 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878 } else {
2879#if DEBUG_GESTURES
2880 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2881 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2882#endif
2883 }
2884 } else {
2885#if DEBUG_GESTURES
2886 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2887 (when - mPointerGesture.tapUpTime) * 0.000001f);
2888#endif
2889 }
Michael Wright227c5542020-07-02 18:30:52 +01002890 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2891 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 }
2893
2894 float deltaX = 0, deltaY = 0;
2895 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2896 const RawPointerData::Pointer& currentPointer =
2897 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2898 const RawPointerData::Pointer& lastPointer =
2899 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2900 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2901 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2902
2903 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2904 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2905
2906 // Move the pointer using a relative motion.
2907 // When using spots, the hover or drag will occur at the position of the anchor spot.
2908 mPointerController->move(deltaX, deltaY);
2909 } else {
2910 mPointerVelocityControl.reset();
2911 }
2912
2913 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002914 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002915#if DEBUG_GESTURES
2916 ALOGD("Gestures: TAP_DRAG");
2917#endif
2918 down = true;
2919 } else {
2920#if DEBUG_GESTURES
2921 ALOGD("Gestures: HOVER");
2922#endif
Michael Wright227c5542020-07-02 18:30:52 +01002923 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002924 *outFinishPreviousGesture = true;
2925 }
2926 mPointerGesture.activeGestureId = 0;
2927 down = false;
2928 }
2929
2930 float x, y;
2931 mPointerController->getPosition(&x, &y);
2932
2933 mPointerGesture.currentGestureIdBits.clear();
2934 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2935 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2936 mPointerGesture.currentGestureProperties[0].clear();
2937 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2938 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2939 mPointerGesture.currentGestureCoords[0].clear();
2940 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2941 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2942 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2943 down ? 1.0f : 0.0f);
2944
2945 if (lastFingerCount == 0 && currentFingerCount != 0) {
2946 mPointerGesture.resetTap();
2947 mPointerGesture.tapDownTime = when;
2948 mPointerGesture.tapX = x;
2949 mPointerGesture.tapY = y;
2950 }
2951 } else {
2952 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2953 // We need to provide feedback for each finger that goes down so we cannot wait
2954 // for the fingers to move before deciding what to do.
2955 //
2956 // The ambiguous case is deciding what to do when there are two fingers down but they
2957 // have not moved enough to determine whether they are part of a drag or part of a
2958 // freeform gesture, or just a press or long-press at the pointer location.
2959 //
2960 // When there are two fingers we start with the PRESS hypothesis and we generate a
2961 // down at the pointer location.
2962 //
2963 // When the two fingers move enough or when additional fingers are added, we make
2964 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2965 ALOG_ASSERT(activeTouchId >= 0);
2966
2967 bool settled = when >=
2968 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002969 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2970 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2971 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002972 *outFinishPreviousGesture = true;
2973 } else if (!settled && currentFingerCount > lastFingerCount) {
2974 // Additional pointers have gone down but not yet settled.
2975 // Reset the gesture.
2976#if DEBUG_GESTURES
2977 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2978 "settle time remaining %0.3fms",
2979 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2980 when) * 0.000001f);
2981#endif
2982 *outCancelPreviousGesture = true;
2983 } else {
2984 // Continue previous gesture.
2985 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2986 }
2987
2988 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002989 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 mPointerGesture.activeGestureId = 0;
2991 mPointerGesture.referenceIdBits.clear();
2992 mPointerVelocityControl.reset();
2993
2994 // Use the centroid and pointer location as the reference points for the gesture.
2995#if DEBUG_GESTURES
2996 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2997 "settle time remaining %0.3fms",
2998 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2999 when) * 0.000001f);
3000#endif
3001 mCurrentRawState.rawPointerData
3002 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3003 &mPointerGesture.referenceTouchY);
3004 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3005 &mPointerGesture.referenceGestureY);
3006 }
3007
3008 // Clear the reference deltas for fingers not yet included in the reference calculation.
3009 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3010 ~mPointerGesture.referenceIdBits.value);
3011 !idBits.isEmpty();) {
3012 uint32_t id = idBits.clearFirstMarkedBit();
3013 mPointerGesture.referenceDeltas[id].dx = 0;
3014 mPointerGesture.referenceDeltas[id].dy = 0;
3015 }
3016 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3017
3018 // Add delta for all fingers and calculate a common movement delta.
3019 float commonDeltaX = 0, commonDeltaY = 0;
3020 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3021 mCurrentCookedState.fingerIdBits.value);
3022 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3023 bool first = (idBits == commonIdBits);
3024 uint32_t id = idBits.clearFirstMarkedBit();
3025 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3026 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3027 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3028 delta.dx += cpd.x - lpd.x;
3029 delta.dy += cpd.y - lpd.y;
3030
3031 if (first) {
3032 commonDeltaX = delta.dx;
3033 commonDeltaY = delta.dy;
3034 } else {
3035 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3036 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3037 }
3038 }
3039
3040 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003041 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003042 float dist[MAX_POINTER_ID + 1];
3043 int32_t distOverThreshold = 0;
3044 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3045 uint32_t id = idBits.clearFirstMarkedBit();
3046 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3047 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3048 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3049 distOverThreshold += 1;
3050 }
3051 }
3052
3053 // Only transition when at least two pointers have moved further than
3054 // the minimum distance threshold.
3055 if (distOverThreshold >= 2) {
3056 if (currentFingerCount > 2) {
3057 // There are more than two pointers, switch to FREEFORM.
3058#if DEBUG_GESTURES
3059 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3060 currentFingerCount);
3061#endif
3062 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003063 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003064 } else {
3065 // There are exactly two pointers.
3066 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3067 uint32_t id1 = idBits.clearFirstMarkedBit();
3068 uint32_t id2 = idBits.firstMarkedBit();
3069 const RawPointerData::Pointer& p1 =
3070 mCurrentRawState.rawPointerData.pointerForId(id1);
3071 const RawPointerData::Pointer& p2 =
3072 mCurrentRawState.rawPointerData.pointerForId(id2);
3073 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3074 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3075 // There are two pointers but they are too far apart for a SWIPE,
3076 // switch to FREEFORM.
3077#if DEBUG_GESTURES
3078 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3079 mutualDistance, mPointerGestureMaxSwipeWidth);
3080#endif
3081 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003082 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003083 } else {
3084 // There are two pointers. Wait for both pointers to start moving
3085 // before deciding whether this is a SWIPE or FREEFORM gesture.
3086 float dist1 = dist[id1];
3087 float dist2 = dist[id2];
3088 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3089 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3090 // Calculate the dot product of the displacement vectors.
3091 // When the vectors are oriented in approximately the same direction,
3092 // the angle betweeen them is near zero and the cosine of the angle
3093 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3094 // mag(v2).
3095 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3096 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3097 float dx1 = delta1.dx * mPointerXZoomScale;
3098 float dy1 = delta1.dy * mPointerYZoomScale;
3099 float dx2 = delta2.dx * mPointerXZoomScale;
3100 float dy2 = delta2.dy * mPointerYZoomScale;
3101 float dot = dx1 * dx2 + dy1 * dy2;
3102 float cosine = dot / (dist1 * dist2); // denominator always > 0
3103 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3104 // Pointers are moving in the same direction. Switch to SWIPE.
3105#if DEBUG_GESTURES
3106 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3107 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3108 "cosine %0.3f >= %0.3f",
3109 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3110 mConfig.pointerGestureMultitouchMinDistance, cosine,
3111 mConfig.pointerGestureSwipeTransitionAngleCosine);
3112#endif
Michael Wright227c5542020-07-02 18:30:52 +01003113 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003114 } else {
3115 // Pointers are moving in different directions. Switch to FREEFORM.
3116#if DEBUG_GESTURES
3117 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3118 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3119 "cosine %0.3f < %0.3f",
3120 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3121 mConfig.pointerGestureMultitouchMinDistance, cosine,
3122 mConfig.pointerGestureSwipeTransitionAngleCosine);
3123#endif
3124 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003125 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003126 }
3127 }
3128 }
3129 }
3130 }
Michael Wright227c5542020-07-02 18:30:52 +01003131 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003132 // Switch from SWIPE to FREEFORM if additional pointers go down.
3133 // Cancel previous gesture.
3134 if (currentFingerCount > 2) {
3135#if DEBUG_GESTURES
3136 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3137 currentFingerCount);
3138#endif
3139 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003140 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003141 }
3142 }
3143
3144 // Move the reference points based on the overall group motion of the fingers
3145 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003146 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003147 (commonDeltaX || commonDeltaY)) {
3148 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3149 uint32_t id = idBits.clearFirstMarkedBit();
3150 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3151 delta.dx = 0;
3152 delta.dy = 0;
3153 }
3154
3155 mPointerGesture.referenceTouchX += commonDeltaX;
3156 mPointerGesture.referenceTouchY += commonDeltaY;
3157
3158 commonDeltaX *= mPointerXMovementScale;
3159 commonDeltaY *= mPointerYMovementScale;
3160
3161 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3162 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3163
3164 mPointerGesture.referenceGestureX += commonDeltaX;
3165 mPointerGesture.referenceGestureY += commonDeltaY;
3166 }
3167
3168 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003169 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3170 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003171 // PRESS or SWIPE mode.
3172#if DEBUG_GESTURES
3173 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3174 "activeGestureId=%d, currentTouchPointerCount=%d",
3175 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3176#endif
3177 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3178
3179 mPointerGesture.currentGestureIdBits.clear();
3180 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3181 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3182 mPointerGesture.currentGestureProperties[0].clear();
3183 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3184 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3185 mPointerGesture.currentGestureCoords[0].clear();
3186 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3187 mPointerGesture.referenceGestureX);
3188 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3189 mPointerGesture.referenceGestureY);
3190 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003191 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003192 // FREEFORM mode.
3193#if DEBUG_GESTURES
3194 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3195 "activeGestureId=%d, currentTouchPointerCount=%d",
3196 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3197#endif
3198 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3199
3200 mPointerGesture.currentGestureIdBits.clear();
3201
3202 BitSet32 mappedTouchIdBits;
3203 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003204 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003205 // Initially, assign the active gesture id to the active touch point
3206 // if there is one. No other touch id bits are mapped yet.
3207 if (!*outCancelPreviousGesture) {
3208 mappedTouchIdBits.markBit(activeTouchId);
3209 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3210 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3211 mPointerGesture.activeGestureId;
3212 } else {
3213 mPointerGesture.activeGestureId = -1;
3214 }
3215 } else {
3216 // Otherwise, assume we mapped all touches from the previous frame.
3217 // Reuse all mappings that are still applicable.
3218 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3219 mCurrentCookedState.fingerIdBits.value;
3220 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3221
3222 // Check whether we need to choose a new active gesture id because the
3223 // current went went up.
3224 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3225 ~mCurrentCookedState.fingerIdBits.value);
3226 !upTouchIdBits.isEmpty();) {
3227 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3228 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3229 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3230 mPointerGesture.activeGestureId = -1;
3231 break;
3232 }
3233 }
3234 }
3235
3236#if DEBUG_GESTURES
3237 ALOGD("Gestures: FREEFORM follow up "
3238 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3239 "activeGestureId=%d",
3240 mappedTouchIdBits.value, usedGestureIdBits.value,
3241 mPointerGesture.activeGestureId);
3242#endif
3243
3244 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3245 for (uint32_t i = 0; i < currentFingerCount; i++) {
3246 uint32_t touchId = idBits.clearFirstMarkedBit();
3247 uint32_t gestureId;
3248 if (!mappedTouchIdBits.hasBit(touchId)) {
3249 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3250 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3251#if DEBUG_GESTURES
3252 ALOGD("Gestures: FREEFORM "
3253 "new mapping for touch id %d -> gesture id %d",
3254 touchId, gestureId);
3255#endif
3256 } else {
3257 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3258#if DEBUG_GESTURES
3259 ALOGD("Gestures: FREEFORM "
3260 "existing mapping for touch id %d -> gesture id %d",
3261 touchId, gestureId);
3262#endif
3263 }
3264 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3265 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3266
3267 const RawPointerData::Pointer& pointer =
3268 mCurrentRawState.rawPointerData.pointerForId(touchId);
3269 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3270 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3271 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3272
3273 mPointerGesture.currentGestureProperties[i].clear();
3274 mPointerGesture.currentGestureProperties[i].id = gestureId;
3275 mPointerGesture.currentGestureProperties[i].toolType =
3276 AMOTION_EVENT_TOOL_TYPE_FINGER;
3277 mPointerGesture.currentGestureCoords[i].clear();
3278 mPointerGesture.currentGestureCoords[i]
3279 .setAxisValue(AMOTION_EVENT_AXIS_X,
3280 mPointerGesture.referenceGestureX + deltaX);
3281 mPointerGesture.currentGestureCoords[i]
3282 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3283 mPointerGesture.referenceGestureY + deltaY);
3284 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3285 1.0f);
3286 }
3287
3288 if (mPointerGesture.activeGestureId < 0) {
3289 mPointerGesture.activeGestureId =
3290 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3291#if DEBUG_GESTURES
3292 ALOGD("Gestures: FREEFORM new "
3293 "activeGestureId=%d",
3294 mPointerGesture.activeGestureId);
3295#endif
3296 }
3297 }
3298 }
3299
3300 mPointerController->setButtonState(mCurrentRawState.buttonState);
3301
3302#if DEBUG_GESTURES
3303 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3304 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3305 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3306 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3307 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3308 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3309 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3310 uint32_t id = idBits.clearFirstMarkedBit();
3311 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3312 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3313 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3314 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3315 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3316 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3317 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3318 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3319 }
3320 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3321 uint32_t id = idBits.clearFirstMarkedBit();
3322 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3323 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3324 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3325 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3326 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3327 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3328 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3329 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3330 }
3331#endif
3332 return true;
3333}
3334
3335void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3336 mPointerSimple.currentCoords.clear();
3337 mPointerSimple.currentProperties.clear();
3338
3339 bool down, hovering;
3340 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3341 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3342 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3343 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3344 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3345 mPointerController->setPosition(x, y);
3346
3347 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3348 down = !hovering;
3349
3350 mPointerController->getPosition(&x, &y);
3351 mPointerSimple.currentCoords.copyFrom(
3352 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3353 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3354 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3355 mPointerSimple.currentProperties.id = 0;
3356 mPointerSimple.currentProperties.toolType =
3357 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3358 } else {
3359 down = false;
3360 hovering = false;
3361 }
3362
3363 dispatchPointerSimple(when, policyFlags, down, hovering);
3364}
3365
3366void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3367 abortPointerSimple(when, policyFlags);
3368}
3369
3370void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3371 mPointerSimple.currentCoords.clear();
3372 mPointerSimple.currentProperties.clear();
3373
3374 bool down, hovering;
3375 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3376 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3377 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3378 float deltaX = 0, deltaY = 0;
3379 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3380 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3381 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3382 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3383 mPointerXMovementScale;
3384 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3385 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3386 mPointerYMovementScale;
3387
3388 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3389 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3390
3391 mPointerController->move(deltaX, deltaY);
3392 } else {
3393 mPointerVelocityControl.reset();
3394 }
3395
3396 down = isPointerDown(mCurrentRawState.buttonState);
3397 hovering = !down;
3398
3399 float x, y;
3400 mPointerController->getPosition(&x, &y);
3401 mPointerSimple.currentCoords.copyFrom(
3402 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3403 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3404 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3405 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3406 hovering ? 0.0f : 1.0f);
3407 mPointerSimple.currentProperties.id = 0;
3408 mPointerSimple.currentProperties.toolType =
3409 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3410 } else {
3411 mPointerVelocityControl.reset();
3412
3413 down = false;
3414 hovering = false;
3415 }
3416
3417 dispatchPointerSimple(when, policyFlags, down, hovering);
3418}
3419
3420void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3421 abortPointerSimple(when, policyFlags);
3422
3423 mPointerVelocityControl.reset();
3424}
3425
3426void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3427 bool hovering) {
3428 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003429
3430 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003431 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003432 mPointerController->clearSpots();
3433 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003434 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003435 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003436 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003437 }
Garfield Tan9514d782020-11-10 16:37:23 -08003438 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003439
3440 float xCursorPosition;
3441 float yCursorPosition;
3442 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3443
3444 if (mPointerSimple.down && !down) {
3445 mPointerSimple.down = false;
3446
3447 // Send up.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003448 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3449 AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
3450 mLastRawState.buttonState, MotionClassification::NONE,
3451 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3452 &mPointerSimple.lastCoords, mOrientedXPrecision,
3453 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3454 mPointerSimple.downTime,
3455 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003456 }
3457
3458 if (mPointerSimple.hovering && !hovering) {
3459 mPointerSimple.hovering = false;
3460
3461 // Send hover exit.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003462 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3463 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3464 mLastRawState.buttonState, MotionClassification::NONE,
3465 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3466 &mPointerSimple.lastCoords, mOrientedXPrecision,
3467 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3468 mPointerSimple.downTime,
3469 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003470 }
3471
3472 if (down) {
3473 if (!mPointerSimple.down) {
3474 mPointerSimple.down = true;
3475 mPointerSimple.downTime = when;
3476
3477 // Send down.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003478 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3479 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3480 mCurrentRawState.buttonState, MotionClassification::NONE,
3481 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3482 &mPointerSimple.currentProperties,
3483 &mPointerSimple.currentCoords, mOrientedXPrecision,
3484 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3485 mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003486 }
3487
3488 // Send move.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003489 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3490 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
3491 mCurrentRawState.buttonState, MotionClassification::NONE,
3492 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3493 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3494 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3495 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003496 }
3497
3498 if (hovering) {
3499 if (!mPointerSimple.hovering) {
3500 mPointerSimple.hovering = true;
3501
3502 // Send hover enter.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003503 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3504 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3505 mCurrentRawState.buttonState, MotionClassification::NONE,
3506 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3507 &mPointerSimple.currentProperties,
3508 &mPointerSimple.currentCoords, mOrientedXPrecision,
3509 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3510 mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003511 }
3512
3513 // Send hover move.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003514 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3515 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3516 mCurrentRawState.buttonState, MotionClassification::NONE,
3517 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3518 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3519 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3520 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003521 }
3522
3523 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3524 float vscroll = mCurrentRawState.rawVScroll;
3525 float hscroll = mCurrentRawState.rawHScroll;
3526 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3527 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3528
3529 // Send scroll.
3530 PointerCoords pointerCoords;
3531 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3532 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3533 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3534
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003535 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3536 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
3537 mCurrentRawState.buttonState, MotionClassification::NONE,
3538 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3539 &mPointerSimple.currentProperties, &pointerCoords,
3540 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3541 yCursorPosition, mPointerSimple.downTime,
3542 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003543 }
3544
3545 // Save state.
3546 if (down || hovering) {
3547 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3548 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3549 } else {
3550 mPointerSimple.reset();
3551 }
3552}
3553
3554void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3555 mPointerSimple.currentCoords.clear();
3556 mPointerSimple.currentProperties.clear();
3557
3558 dispatchPointerSimple(when, policyFlags, false, false);
3559}
3560
3561void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3562 int32_t action, int32_t actionButton, int32_t flags,
3563 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3564 const PointerProperties* properties,
3565 const PointerCoords* coords, const uint32_t* idToIndex,
3566 BitSet32 idBits, int32_t changedId, float xPrecision,
3567 float yPrecision, nsecs_t downTime) {
3568 PointerCoords pointerCoords[MAX_POINTERS];
3569 PointerProperties pointerProperties[MAX_POINTERS];
3570 uint32_t pointerCount = 0;
3571 while (!idBits.isEmpty()) {
3572 uint32_t id = idBits.clearFirstMarkedBit();
3573 uint32_t index = idToIndex[id];
3574 pointerProperties[pointerCount].copyFrom(properties[index]);
3575 pointerCoords[pointerCount].copyFrom(coords[index]);
3576
3577 if (changedId >= 0 && id == uint32_t(changedId)) {
3578 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3579 }
3580
3581 pointerCount += 1;
3582 }
3583
3584 ALOG_ASSERT(pointerCount != 0);
3585
3586 if (changedId >= 0 && pointerCount == 1) {
3587 // Replace initial down and final up action.
3588 // We can compare the action without masking off the changed pointer index
3589 // because we know the index is 0.
3590 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3591 action = AMOTION_EVENT_ACTION_DOWN;
3592 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003593 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3594 action = AMOTION_EVENT_ACTION_CANCEL;
3595 } else {
3596 action = AMOTION_EVENT_ACTION_UP;
3597 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598 } else {
3599 // Can't happen.
3600 ALOG_ASSERT(false);
3601 }
3602 }
3603 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3604 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003605 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3607 }
3608 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3609 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003610 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003611 std::for_each(frames.begin(), frames.end(),
3612 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003613 getContext()->notifyMotion(when, deviceId, source, displayId, policyFlags, action, actionButton,
3614 flags, metaState, buttonState, MotionClassification::NONE, edgeFlags,
3615 pointerCount, pointerProperties, pointerCoords, xPrecision,
3616 yPrecision, xCursorPosition, yCursorPosition, downTime,
3617 std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003618}
3619
3620bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3621 const PointerCoords* inCoords,
3622 const uint32_t* inIdToIndex,
3623 PointerProperties* outProperties,
3624 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3625 BitSet32 idBits) const {
3626 bool changed = false;
3627 while (!idBits.isEmpty()) {
3628 uint32_t id = idBits.clearFirstMarkedBit();
3629 uint32_t inIndex = inIdToIndex[id];
3630 uint32_t outIndex = outIdToIndex[id];
3631
3632 const PointerProperties& curInProperties = inProperties[inIndex];
3633 const PointerCoords& curInCoords = inCoords[inIndex];
3634 PointerProperties& curOutProperties = outProperties[outIndex];
3635 PointerCoords& curOutCoords = outCoords[outIndex];
3636
3637 if (curInProperties != curOutProperties) {
3638 curOutProperties.copyFrom(curInProperties);
3639 changed = true;
3640 }
3641
3642 if (curInCoords != curOutCoords) {
3643 curOutCoords.copyFrom(curInCoords);
3644 changed = true;
3645 }
3646 }
3647 return changed;
3648}
3649
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003650void TouchInputMapper::cancelTouch(nsecs_t when) {
3651 abortPointerUsage(when, 0 /*policyFlags*/);
3652 abortTouches(when, 0 /* policyFlags*/);
3653}
3654
Arthur Hung4197f6b2020-03-16 15:39:59 +08003655// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003656void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003657 // Scale to surface coordinate.
3658 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3659 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3660
arthurhunga36b28e2020-12-29 20:28:15 +08003661 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3662 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3663
Arthur Hung4197f6b2020-03-16 15:39:59 +08003664 // Rotate to surface coordinate.
3665 // 0 - no swap and reverse.
3666 // 90 - swap x/y and reverse y.
3667 // 180 - reverse x, y.
3668 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003669 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003670 case DISPLAY_ORIENTATION_0:
3671 x = xScaled + mXTranslate;
3672 y = yScaled + mYTranslate;
3673 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003674 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003675 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003676 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003677 break;
3678 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003679 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3680 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003681 break;
3682 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003683 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003684 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003685 break;
3686 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003687 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003688 }
3689}
3690
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003691bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003692 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3693 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3694
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003695 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003696 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003697 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003698 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003699}
3700
3701const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3702 for (const VirtualKey& virtualKey : mVirtualKeys) {
3703#if DEBUG_VIRTUAL_KEYS
3704 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3705 "left=%d, top=%d, right=%d, bottom=%d",
3706 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3707 virtualKey.hitRight, virtualKey.hitBottom);
3708#endif
3709
3710 if (virtualKey.isHit(x, y)) {
3711 return &virtualKey;
3712 }
3713 }
3714
3715 return nullptr;
3716}
3717
3718void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3719 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3720 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3721
3722 current->rawPointerData.clearIdBits();
3723
3724 if (currentPointerCount == 0) {
3725 // No pointers to assign.
3726 return;
3727 }
3728
3729 if (lastPointerCount == 0) {
3730 // All pointers are new.
3731 for (uint32_t i = 0; i < currentPointerCount; i++) {
3732 uint32_t id = i;
3733 current->rawPointerData.pointers[i].id = id;
3734 current->rawPointerData.idToIndex[id] = i;
3735 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3736 }
3737 return;
3738 }
3739
3740 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3741 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3742 // Only one pointer and no change in count so it must have the same id as before.
3743 uint32_t id = last->rawPointerData.pointers[0].id;
3744 current->rawPointerData.pointers[0].id = id;
3745 current->rawPointerData.idToIndex[id] = 0;
3746 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3747 return;
3748 }
3749
3750 // General case.
3751 // We build a heap of squared euclidean distances between current and last pointers
3752 // associated with the current and last pointer indices. Then, we find the best
3753 // match (by distance) for each current pointer.
3754 // The pointers must have the same tool type but it is possible for them to
3755 // transition from hovering to touching or vice-versa while retaining the same id.
3756 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3757
3758 uint32_t heapSize = 0;
3759 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3760 currentPointerIndex++) {
3761 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3762 lastPointerIndex++) {
3763 const RawPointerData::Pointer& currentPointer =
3764 current->rawPointerData.pointers[currentPointerIndex];
3765 const RawPointerData::Pointer& lastPointer =
3766 last->rawPointerData.pointers[lastPointerIndex];
3767 if (currentPointer.toolType == lastPointer.toolType) {
3768 int64_t deltaX = currentPointer.x - lastPointer.x;
3769 int64_t deltaY = currentPointer.y - lastPointer.y;
3770
3771 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3772
3773 // Insert new element into the heap (sift up).
3774 heap[heapSize].currentPointerIndex = currentPointerIndex;
3775 heap[heapSize].lastPointerIndex = lastPointerIndex;
3776 heap[heapSize].distance = distance;
3777 heapSize += 1;
3778 }
3779 }
3780 }
3781
3782 // Heapify
3783 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3784 startIndex -= 1;
3785 for (uint32_t parentIndex = startIndex;;) {
3786 uint32_t childIndex = parentIndex * 2 + 1;
3787 if (childIndex >= heapSize) {
3788 break;
3789 }
3790
3791 if (childIndex + 1 < heapSize &&
3792 heap[childIndex + 1].distance < heap[childIndex].distance) {
3793 childIndex += 1;
3794 }
3795
3796 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3797 break;
3798 }
3799
3800 swap(heap[parentIndex], heap[childIndex]);
3801 parentIndex = childIndex;
3802 }
3803 }
3804
3805#if DEBUG_POINTER_ASSIGNMENT
3806 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3807 for (size_t i = 0; i < heapSize; i++) {
3808 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3809 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3810 }
3811#endif
3812
3813 // Pull matches out by increasing order of distance.
3814 // To avoid reassigning pointers that have already been matched, the loop keeps track
3815 // of which last and current pointers have been matched using the matchedXXXBits variables.
3816 // It also tracks the used pointer id bits.
3817 BitSet32 matchedLastBits(0);
3818 BitSet32 matchedCurrentBits(0);
3819 BitSet32 usedIdBits(0);
3820 bool first = true;
3821 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3822 while (heapSize > 0) {
3823 if (first) {
3824 // The first time through the loop, we just consume the root element of
3825 // the heap (the one with smallest distance).
3826 first = false;
3827 } else {
3828 // Previous iterations consumed the root element of the heap.
3829 // Pop root element off of the heap (sift down).
3830 heap[0] = heap[heapSize];
3831 for (uint32_t parentIndex = 0;;) {
3832 uint32_t childIndex = parentIndex * 2 + 1;
3833 if (childIndex >= heapSize) {
3834 break;
3835 }
3836
3837 if (childIndex + 1 < heapSize &&
3838 heap[childIndex + 1].distance < heap[childIndex].distance) {
3839 childIndex += 1;
3840 }
3841
3842 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3843 break;
3844 }
3845
3846 swap(heap[parentIndex], heap[childIndex]);
3847 parentIndex = childIndex;
3848 }
3849
3850#if DEBUG_POINTER_ASSIGNMENT
3851 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003852 for (size_t j = 0; j < heapSize; j++) {
3853 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3854 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003855 }
3856#endif
3857 }
3858
3859 heapSize -= 1;
3860
3861 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3862 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3863
3864 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3865 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3866
3867 matchedCurrentBits.markBit(currentPointerIndex);
3868 matchedLastBits.markBit(lastPointerIndex);
3869
3870 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3871 current->rawPointerData.pointers[currentPointerIndex].id = id;
3872 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3873 current->rawPointerData.markIdBit(id,
3874 current->rawPointerData.isHovering(
3875 currentPointerIndex));
3876 usedIdBits.markBit(id);
3877
3878#if DEBUG_POINTER_ASSIGNMENT
3879 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3880 ", distance=%" PRIu64,
3881 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3882#endif
3883 break;
3884 }
3885 }
3886
3887 // Assign fresh ids to pointers that were not matched in the process.
3888 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3889 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3890 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3891
3892 current->rawPointerData.pointers[currentPointerIndex].id = id;
3893 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3894 current->rawPointerData.markIdBit(id,
3895 current->rawPointerData.isHovering(currentPointerIndex));
3896
3897#if DEBUG_POINTER_ASSIGNMENT
3898 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3899#endif
3900 }
3901}
3902
3903int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3904 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3905 return AKEY_STATE_VIRTUAL;
3906 }
3907
3908 for (const VirtualKey& virtualKey : mVirtualKeys) {
3909 if (virtualKey.keyCode == keyCode) {
3910 return AKEY_STATE_UP;
3911 }
3912 }
3913
3914 return AKEY_STATE_UNKNOWN;
3915}
3916
3917int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3918 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3919 return AKEY_STATE_VIRTUAL;
3920 }
3921
3922 for (const VirtualKey& virtualKey : mVirtualKeys) {
3923 if (virtualKey.scanCode == scanCode) {
3924 return AKEY_STATE_UP;
3925 }
3926 }
3927
3928 return AKEY_STATE_UNKNOWN;
3929}
3930
3931bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3932 const int32_t* keyCodes, uint8_t* outFlags) {
3933 for (const VirtualKey& virtualKey : mVirtualKeys) {
3934 for (size_t i = 0; i < numCodes; i++) {
3935 if (virtualKey.keyCode == keyCodes[i]) {
3936 outFlags[i] = 1;
3937 }
3938 }
3939 }
3940
3941 return true;
3942}
3943
3944std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3945 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003946 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003947 return std::make_optional(mPointerController->getDisplayId());
3948 } else {
3949 return std::make_optional(mViewport.displayId);
3950 }
3951 }
3952 return std::nullopt;
3953}
3954
3955} // namespace android