blob: fb30b88b8d5aeb3e07134a2698237f62efa4d923 [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 }
Michael Wright227c5542020-07-02 18:30:52 +0100611 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700612 mParameters.hasAssociatedDisplay) {
613 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100614 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700615 if (hasStylus()) {
616 mSource |= AINPUT_SOURCE_STYLUS;
617 }
618 if (hasExternalStylus()) {
619 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
620 }
Michael Wright227c5542020-07-02 18:30:52 +0100621 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700622 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100623 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700624 } else {
625 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100626 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700627 }
628
629 // Ensure we have valid X and Y axes.
630 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
631 ALOGW("Touch device '%s' did not report support for X or Y axis! "
632 "The device will be inoperable.",
633 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100634 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700635 return;
636 }
637
638 // Get associated display dimensions.
639 std::optional<DisplayViewport> newViewport = findViewport();
640 if (!newViewport) {
641 ALOGI("Touch device '%s' could not query the properties of its associated "
642 "display. The device will be inoperable until the display size "
643 "becomes available.",
644 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100645 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700646 return;
647 }
648
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000649 if (!newViewport->isActive) {
650 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
651 getDeviceName().c_str(), getDeviceId());
652 mDeviceMode = DeviceMode::DISABLED;
653 return;
654 }
655
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700656 // Raw width and height in the natural orientation.
657 int32_t rawWidth = mRawPointerAxes.getRawWidth();
658 int32_t rawHeight = mRawPointerAxes.getRawHeight();
659
660 bool viewportChanged = mViewport != *newViewport;
661 if (viewportChanged) {
662 mViewport = *newViewport;
663
Michael Wright227c5542020-07-02 18:30:52 +0100664 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700665 // Convert rotated viewport to natural surface coordinates.
666 int32_t naturalLogicalWidth, naturalLogicalHeight;
667 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
668 int32_t naturalPhysicalLeft, naturalPhysicalTop;
669 int32_t naturalDeviceWidth, naturalDeviceHeight;
670 switch (mViewport.orientation) {
671 case DISPLAY_ORIENTATION_90:
672 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
673 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
674 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
675 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800676 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700677 naturalPhysicalTop = mViewport.physicalLeft;
678 naturalDeviceWidth = mViewport.deviceHeight;
679 naturalDeviceHeight = mViewport.deviceWidth;
680 break;
681 case DISPLAY_ORIENTATION_180:
682 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
683 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
684 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
685 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
686 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
687 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
688 naturalDeviceWidth = mViewport.deviceWidth;
689 naturalDeviceHeight = mViewport.deviceHeight;
690 break;
691 case DISPLAY_ORIENTATION_270:
692 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
693 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
694 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
695 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
696 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800697 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700698 naturalDeviceWidth = mViewport.deviceHeight;
699 naturalDeviceHeight = mViewport.deviceWidth;
700 break;
701 case DISPLAY_ORIENTATION_0:
702 default:
703 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
704 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
705 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
706 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
707 naturalPhysicalLeft = mViewport.physicalLeft;
708 naturalPhysicalTop = mViewport.physicalTop;
709 naturalDeviceWidth = mViewport.deviceWidth;
710 naturalDeviceHeight = mViewport.deviceHeight;
711 break;
712 }
713
714 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
715 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
716 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
717 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
718 }
719
720 mPhysicalWidth = naturalPhysicalWidth;
721 mPhysicalHeight = naturalPhysicalHeight;
722 mPhysicalLeft = naturalPhysicalLeft;
723 mPhysicalTop = naturalPhysicalTop;
724
Arthur Hung4197f6b2020-03-16 15:39:59 +0800725 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
726 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700727 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
728 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800729 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
730 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700731
732 mSurfaceOrientation =
733 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
734 } else {
735 mPhysicalWidth = rawWidth;
736 mPhysicalHeight = rawHeight;
737 mPhysicalLeft = 0;
738 mPhysicalTop = 0;
739
Arthur Hung4197f6b2020-03-16 15:39:59 +0800740 mRawSurfaceWidth = rawWidth;
741 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700742 mSurfaceLeft = 0;
743 mSurfaceTop = 0;
744 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
745 }
746 }
747
748 // If moving between pointer modes, need to reset some state.
749 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
750 if (deviceModeChanged) {
751 mOrientedRanges.clear();
752 }
753
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800754 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
755 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100756 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800757 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
758 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800759 if (mPointerController == nullptr) {
760 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700761 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800762 if (mConfig.pointerCapture) {
763 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
764 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700765 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100766 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700767 }
768
769 if (viewportChanged || deviceModeChanged) {
770 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
771 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800772 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700773 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
774
775 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800776 mXScale = float(mRawSurfaceWidth) / rawWidth;
777 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700778 mXTranslate = -mSurfaceLeft;
779 mYTranslate = -mSurfaceTop;
780 mXPrecision = 1.0f / mXScale;
781 mYPrecision = 1.0f / mYScale;
782
783 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
784 mOrientedRanges.x.source = mSource;
785 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
786 mOrientedRanges.y.source = mSource;
787
788 configureVirtualKeys();
789
790 // Scale factor for terms that are not oriented in a particular axis.
791 // If the pixels are square then xScale == yScale otherwise we fake it
792 // by choosing an average.
793 mGeometricScale = avg(mXScale, mYScale);
794
795 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800796 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700797
798 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100799 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700800 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
801 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
802 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
803 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
804 } else {
805 mSizeScale = 0.0f;
806 }
807
808 mOrientedRanges.haveTouchSize = true;
809 mOrientedRanges.haveToolSize = true;
810 mOrientedRanges.haveSize = true;
811
812 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
813 mOrientedRanges.touchMajor.source = mSource;
814 mOrientedRanges.touchMajor.min = 0;
815 mOrientedRanges.touchMajor.max = diagonalSize;
816 mOrientedRanges.touchMajor.flat = 0;
817 mOrientedRanges.touchMajor.fuzz = 0;
818 mOrientedRanges.touchMajor.resolution = 0;
819
820 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
821 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
822
823 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
824 mOrientedRanges.toolMajor.source = mSource;
825 mOrientedRanges.toolMajor.min = 0;
826 mOrientedRanges.toolMajor.max = diagonalSize;
827 mOrientedRanges.toolMajor.flat = 0;
828 mOrientedRanges.toolMajor.fuzz = 0;
829 mOrientedRanges.toolMajor.resolution = 0;
830
831 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
832 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
833
834 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
835 mOrientedRanges.size.source = mSource;
836 mOrientedRanges.size.min = 0;
837 mOrientedRanges.size.max = 1.0;
838 mOrientedRanges.size.flat = 0;
839 mOrientedRanges.size.fuzz = 0;
840 mOrientedRanges.size.resolution = 0;
841 } else {
842 mSizeScale = 0.0f;
843 }
844
845 // Pressure factors.
846 mPressureScale = 0;
847 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100848 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
849 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700850 if (mCalibration.havePressureScale) {
851 mPressureScale = mCalibration.pressureScale;
852 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
853 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
854 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
855 }
856 }
857
858 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
859 mOrientedRanges.pressure.source = mSource;
860 mOrientedRanges.pressure.min = 0;
861 mOrientedRanges.pressure.max = pressureMax;
862 mOrientedRanges.pressure.flat = 0;
863 mOrientedRanges.pressure.fuzz = 0;
864 mOrientedRanges.pressure.resolution = 0;
865
866 // Tilt
867 mTiltXCenter = 0;
868 mTiltXScale = 0;
869 mTiltYCenter = 0;
870 mTiltYScale = 0;
871 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
872 if (mHaveTilt) {
873 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
874 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
875 mTiltXScale = M_PI / 180;
876 mTiltYScale = M_PI / 180;
877
878 mOrientedRanges.haveTilt = true;
879
880 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
881 mOrientedRanges.tilt.source = mSource;
882 mOrientedRanges.tilt.min = 0;
883 mOrientedRanges.tilt.max = M_PI_2;
884 mOrientedRanges.tilt.flat = 0;
885 mOrientedRanges.tilt.fuzz = 0;
886 mOrientedRanges.tilt.resolution = 0;
887 }
888
889 // Orientation
890 mOrientationScale = 0;
891 if (mHaveTilt) {
892 mOrientedRanges.haveOrientation = true;
893
894 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
895 mOrientedRanges.orientation.source = mSource;
896 mOrientedRanges.orientation.min = -M_PI;
897 mOrientedRanges.orientation.max = M_PI;
898 mOrientedRanges.orientation.flat = 0;
899 mOrientedRanges.orientation.fuzz = 0;
900 mOrientedRanges.orientation.resolution = 0;
901 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100902 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100904 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700905 if (mRawPointerAxes.orientation.valid) {
906 if (mRawPointerAxes.orientation.maxValue > 0) {
907 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
908 } else if (mRawPointerAxes.orientation.minValue < 0) {
909 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
910 } else {
911 mOrientationScale = 0;
912 }
913 }
914 }
915
916 mOrientedRanges.haveOrientation = true;
917
918 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
919 mOrientedRanges.orientation.source = mSource;
920 mOrientedRanges.orientation.min = -M_PI_2;
921 mOrientedRanges.orientation.max = M_PI_2;
922 mOrientedRanges.orientation.flat = 0;
923 mOrientedRanges.orientation.fuzz = 0;
924 mOrientedRanges.orientation.resolution = 0;
925 }
926
927 // Distance
928 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100929 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
930 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 if (mCalibration.haveDistanceScale) {
932 mDistanceScale = mCalibration.distanceScale;
933 } else {
934 mDistanceScale = 1.0f;
935 }
936 }
937
938 mOrientedRanges.haveDistance = true;
939
940 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
941 mOrientedRanges.distance.source = mSource;
942 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
943 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
944 mOrientedRanges.distance.flat = 0;
945 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
946 mOrientedRanges.distance.resolution = 0;
947 }
948
949 // Compute oriented precision, scales and ranges.
950 // Note that the maximum value reported is an inclusive maximum value so it is one
951 // unit less than the total width or height of surface.
952 switch (mSurfaceOrientation) {
953 case DISPLAY_ORIENTATION_90:
954 case DISPLAY_ORIENTATION_270:
955 mOrientedXPrecision = mYPrecision;
956 mOrientedYPrecision = mXPrecision;
957
958 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800959 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700960 mOrientedRanges.x.flat = 0;
961 mOrientedRanges.x.fuzz = 0;
962 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
963
964 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800965 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966 mOrientedRanges.y.flat = 0;
967 mOrientedRanges.y.fuzz = 0;
968 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
969 break;
970
971 default:
972 mOrientedXPrecision = mXPrecision;
973 mOrientedYPrecision = mYPrecision;
974
975 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800976 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977 mOrientedRanges.x.flat = 0;
978 mOrientedRanges.x.fuzz = 0;
979 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
980
981 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800982 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700983 mOrientedRanges.y.flat = 0;
984 mOrientedRanges.y.fuzz = 0;
985 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
986 break;
987 }
988
989 // Location
990 updateAffineTransformation();
991
Michael Wright227c5542020-07-02 18:30:52 +0100992 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700993 // Compute pointer gesture detection parameters.
994 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +0800995 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996
997 // Scale movements such that one whole swipe of the touch pad covers a
998 // given area relative to the diagonal size of the display when no acceleration
999 // is applied.
1000 // Assume that the touch pad has a square aspect ratio such that movements in
1001 // X and Y of the same number of raw units cover the same physical distance.
1002 mPointerXMovementScale =
1003 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1004 mPointerYMovementScale = mPointerXMovementScale;
1005
1006 // Scale zooms to cover a smaller range of the display than movements do.
1007 // This value determines the area around the pointer that is affected by freeform
1008 // pointer gestures.
1009 mPointerXZoomScale =
1010 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1011 mPointerYZoomScale = mPointerXZoomScale;
1012
1013 // Max width between pointers to detect a swipe gesture is more than some fraction
1014 // of the diagonal axis of the touch pad. Touches that are wider than this are
1015 // translated into freeform gestures.
1016 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1017
1018 // Abort current pointer usages because the state has changed.
1019 abortPointerUsage(when, 0 /*policyFlags*/);
1020 }
1021
1022 // Inform the dispatcher about the changes.
1023 *outResetNeeded = true;
1024 bumpGeneration();
1025 }
1026}
1027
1028void TouchInputMapper::dumpSurface(std::string& dump) {
1029 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001030 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1031 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1033 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001034 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1035 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001036 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1037 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1038 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1039 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1040 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1041}
1042
1043void TouchInputMapper::configureVirtualKeys() {
1044 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001045 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001046
1047 mVirtualKeys.clear();
1048
1049 if (virtualKeyDefinitions.size() == 0) {
1050 return;
1051 }
1052
1053 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1054 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1055 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1056 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1057
1058 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1059 VirtualKey virtualKey;
1060
1061 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1062 int32_t keyCode;
1063 int32_t dummyKeyMetaState;
1064 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001065 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1066 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1068 continue; // drop the key
1069 }
1070
1071 virtualKey.keyCode = keyCode;
1072 virtualKey.flags = flags;
1073
1074 // convert the key definition's display coordinates into touch coordinates for a hit box
1075 int32_t halfWidth = virtualKeyDefinition.width / 2;
1076 int32_t halfHeight = virtualKeyDefinition.height / 2;
1077
1078 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001079 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001080 touchScreenLeft;
1081 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001082 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001083 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001084 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1085 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001087 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1088 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001089 touchScreenTop;
1090 mVirtualKeys.push_back(virtualKey);
1091 }
1092}
1093
1094void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1095 if (!mVirtualKeys.empty()) {
1096 dump += INDENT3 "Virtual Keys:\n";
1097
1098 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1099 const VirtualKey& virtualKey = mVirtualKeys[i];
1100 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1101 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1102 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1103 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1104 }
1105 }
1106}
1107
1108void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001109 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110 Calibration& out = mCalibration;
1111
1112 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001113 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001114 String8 sizeCalibrationString;
1115 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1116 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001117 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001118 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001119 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001120 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001121 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001122 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001123 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001124 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001125 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 } else if (sizeCalibrationString != "default") {
1127 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1128 }
1129 }
1130
1131 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1132 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1133 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1134
1135 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 String8 pressureCalibrationString;
1138 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1139 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (pressureCalibrationString != "default") {
1146 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1147 pressureCalibrationString.string());
1148 }
1149 }
1150
1151 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1152
1153 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001154 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 String8 orientationCalibrationString;
1156 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1157 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001158 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001160 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001161 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001163 } else if (orientationCalibrationString != "default") {
1164 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1165 orientationCalibrationString.string());
1166 }
1167 }
1168
1169 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 String8 distanceCalibrationString;
1172 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1173 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001174 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001176 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 } else if (distanceCalibrationString != "default") {
1178 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1179 distanceCalibrationString.string());
1180 }
1181 }
1182
1183 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1184
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 String8 coverageCalibrationString;
1187 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1188 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 } else if (coverageCalibrationString != "default") {
1193 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1194 coverageCalibrationString.string());
1195 }
1196 }
1197}
1198
1199void TouchInputMapper::resolveCalibration() {
1200 // Size
1201 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001202 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1203 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 }
1205 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001206 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 }
1208
1209 // Pressure
1210 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001211 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1212 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 }
1214 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001215 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 }
1217
1218 // Orientation
1219 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001220 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1221 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 }
1223 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001224 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 }
1226
1227 // Distance
1228 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001229 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1230 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 }
1232 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001233 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 }
1235
1236 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001237 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1238 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 }
1240}
1241
1242void TouchInputMapper::dumpCalibration(std::string& dump) {
1243 dump += INDENT3 "Calibration:\n";
1244
1245 // Size
1246 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001247 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 dump += INDENT4 "touch.size.calibration: none\n";
1249 break;
Michael Wright227c5542020-07-02 18:30:52 +01001250 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 dump += INDENT4 "touch.size.calibration: geometric\n";
1252 break;
Michael Wright227c5542020-07-02 18:30:52 +01001253 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 dump += INDENT4 "touch.size.calibration: diameter\n";
1255 break;
Michael Wright227c5542020-07-02 18:30:52 +01001256 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 dump += INDENT4 "touch.size.calibration: box\n";
1258 break;
Michael Wright227c5542020-07-02 18:30:52 +01001259 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 dump += INDENT4 "touch.size.calibration: area\n";
1261 break;
1262 default:
1263 ALOG_ASSERT(false);
1264 }
1265
1266 if (mCalibration.haveSizeScale) {
1267 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1268 }
1269
1270 if (mCalibration.haveSizeBias) {
1271 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1272 }
1273
1274 if (mCalibration.haveSizeIsSummed) {
1275 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1276 toString(mCalibration.sizeIsSummed));
1277 }
1278
1279 // Pressure
1280 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001281 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 dump += INDENT4 "touch.pressure.calibration: none\n";
1283 break;
Michael Wright227c5542020-07-02 18:30:52 +01001284 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 dump += INDENT4 "touch.pressure.calibration: physical\n";
1286 break;
Michael Wright227c5542020-07-02 18:30:52 +01001287 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1289 break;
1290 default:
1291 ALOG_ASSERT(false);
1292 }
1293
1294 if (mCalibration.havePressureScale) {
1295 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1296 }
1297
1298 // Orientation
1299 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001300 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += INDENT4 "touch.orientation.calibration: none\n";
1302 break;
Michael Wright227c5542020-07-02 18:30:52 +01001303 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1305 break;
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.orientation.calibration: vector\n";
1308 break;
1309 default:
1310 ALOG_ASSERT(false);
1311 }
1312
1313 // Distance
1314 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.distance.calibration: none\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.distance.calibration: scaled\n";
1320 break;
1321 default:
1322 ALOG_ASSERT(false);
1323 }
1324
1325 if (mCalibration.haveDistanceScale) {
1326 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1327 }
1328
1329 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.coverage.calibration: none\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.coverage.calibration: box\n";
1335 break;
1336 default:
1337 ALOG_ASSERT(false);
1338 }
1339}
1340
1341void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1342 dump += INDENT3 "Affine Transformation:\n";
1343
1344 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1345 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1346 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1347 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1348 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1349 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1350}
1351
1352void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001353 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001354 mSurfaceOrientation);
1355}
1356
1357void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001358 mCursorButtonAccumulator.reset(getDeviceContext());
1359 mCursorScrollAccumulator.reset(getDeviceContext());
1360 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361
1362 mPointerVelocityControl.reset();
1363 mWheelXVelocityControl.reset();
1364 mWheelYVelocityControl.reset();
1365
1366 mRawStatesPending.clear();
1367 mCurrentRawState.clear();
1368 mCurrentCookedState.clear();
1369 mLastRawState.clear();
1370 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001371 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001372 mSentHoverEnter = false;
1373 mHavePointerIds = false;
1374 mCurrentMotionAborted = false;
1375 mDownTime = 0;
1376
1377 mCurrentVirtualKey.down = false;
1378
1379 mPointerGesture.reset();
1380 mPointerSimple.reset();
1381 resetExternalStylus();
1382
1383 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001384 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001385 mPointerController->clearSpots();
1386 }
1387
1388 InputMapper::reset(when);
1389}
1390
1391void TouchInputMapper::resetExternalStylus() {
1392 mExternalStylusState.clear();
1393 mExternalStylusId = -1;
1394 mExternalStylusFusionTimeout = LLONG_MAX;
1395 mExternalStylusDataPending = false;
1396}
1397
1398void TouchInputMapper::clearStylusDataPendingFlags() {
1399 mExternalStylusDataPending = false;
1400 mExternalStylusFusionTimeout = LLONG_MAX;
1401}
1402
1403void TouchInputMapper::process(const RawEvent* rawEvent) {
1404 mCursorButtonAccumulator.process(rawEvent);
1405 mCursorScrollAccumulator.process(rawEvent);
1406 mTouchButtonAccumulator.process(rawEvent);
1407
1408 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1409 sync(rawEvent->when);
1410 }
1411}
1412
1413void TouchInputMapper::sync(nsecs_t when) {
1414 const RawState* last =
1415 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1416
1417 // Push a new state.
1418 mRawStatesPending.emplace_back();
1419
1420 RawState* next = &mRawStatesPending.back();
1421 next->clear();
1422 next->when = when;
1423
1424 // Sync button state.
1425 next->buttonState =
1426 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1427
1428 // Sync scroll
1429 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1430 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1431 mCursorScrollAccumulator.finishSync();
1432
1433 // Sync touch
1434 syncTouch(when, next);
1435
1436 // Assign pointer ids.
1437 if (!mHavePointerIds) {
1438 assignPointerIds(last, next);
1439 }
1440
1441#if DEBUG_RAW_EVENTS
1442 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001443 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1445 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001446 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1447 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001448#endif
1449
1450 processRawTouches(false /*timeout*/);
1451}
1452
1453void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001454 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455 // Drop all input if the device is disabled.
1456 mCurrentRawState.clear();
1457 mRawStatesPending.clear();
1458 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 {
Michael Wright227c5542020-07-02 18:30:52 +01001589 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590 mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001591 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1592 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001593
1594 mPointerController->setButtonState(mCurrentRawState.buttonState);
1595 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1596 mCurrentCookedState.cookedPointerData.idToIndex,
1597 mCurrentCookedState.cookedPointerData.touchingIdBits,
1598 mViewport.displayId);
1599 }
1600
1601 if (!mCurrentMotionAborted) {
1602 dispatchButtonRelease(when, policyFlags);
1603 dispatchHoverExit(when, policyFlags);
1604 dispatchTouches(when, policyFlags);
1605 dispatchHoverEnterAndMove(when, policyFlags);
1606 dispatchButtonPress(when, policyFlags);
1607 }
1608
1609 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1610 mCurrentMotionAborted = false;
1611 }
1612 }
1613
1614 // Synthesize key up from raw buttons if needed.
1615 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1616 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1617 mCurrentCookedState.buttonState);
1618
1619 // Clear some transient state.
1620 mCurrentRawState.rawVScroll = 0;
1621 mCurrentRawState.rawHScroll = 0;
1622
1623 // Copy current touch to last touch in preparation for the next cycle.
1624 mLastRawState.copyFrom(mCurrentRawState);
1625 mLastCookedState.copyFrom(mCurrentCookedState);
1626}
1627
1628void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001629 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1631 }
1632}
1633
1634void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1635 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1636 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1637
1638 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1639 float pressure = mExternalStylusState.pressure;
1640 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1641 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1642 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1643 }
1644 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1645 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1646
1647 PointerProperties& properties =
1648 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1649 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1650 properties.toolType = mExternalStylusState.toolType;
1651 }
1652 }
1653}
1654
1655bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001656 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001657 return false;
1658 }
1659
1660 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1661 state.rawPointerData.pointerCount != 0;
1662 if (initialDown) {
1663 if (mExternalStylusState.pressure != 0.0f) {
1664#if DEBUG_STYLUS_FUSION
1665 ALOGD("Have both stylus and touch data, beginning fusion");
1666#endif
1667 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1668 } else if (timeout) {
1669#if DEBUG_STYLUS_FUSION
1670 ALOGD("Timeout expired, assuming touch is not a stylus.");
1671#endif
1672 resetExternalStylus();
1673 } else {
1674 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1675 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1676 }
1677#if DEBUG_STYLUS_FUSION
1678 ALOGD("No stylus data but stylus is connected, requesting timeout "
1679 "(%" PRId64 "ms)",
1680 mExternalStylusFusionTimeout);
1681#endif
1682 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1683 return true;
1684 }
1685 }
1686
1687 // Check if the stylus pointer has gone up.
1688 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1689#if DEBUG_STYLUS_FUSION
1690 ALOGD("Stylus pointer is going up");
1691#endif
1692 mExternalStylusId = -1;
1693 }
1694
1695 return false;
1696}
1697
1698void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001699 if (mDeviceMode == DeviceMode::POINTER) {
1700 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001701 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1702 }
Michael Wright227c5542020-07-02 18:30:52 +01001703 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001704 if (mExternalStylusFusionTimeout < when) {
1705 processRawTouches(true /*timeout*/);
1706 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1707 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1708 }
1709 }
1710}
1711
1712void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1713 mExternalStylusState.copyFrom(state);
1714 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1715 // We're either in the middle of a fused stream of data or we're waiting on data before
1716 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1717 // data.
1718 mExternalStylusDataPending = true;
1719 processRawTouches(false /*timeout*/);
1720 }
1721}
1722
1723bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1724 // Check for release of a virtual key.
1725 if (mCurrentVirtualKey.down) {
1726 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1727 // Pointer went up while virtual key was down.
1728 mCurrentVirtualKey.down = false;
1729 if (!mCurrentVirtualKey.ignored) {
1730#if DEBUG_VIRTUAL_KEYS
1731 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1732 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1733#endif
1734 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1735 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1736 }
1737 return true;
1738 }
1739
1740 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1741 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1742 const RawPointerData::Pointer& pointer =
1743 mCurrentRawState.rawPointerData.pointerForId(id);
1744 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1745 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1746 // Pointer is still within the space of the virtual key.
1747 return true;
1748 }
1749 }
1750
1751 // Pointer left virtual key area or another pointer also went down.
1752 // Send key cancellation but do not consume the touch yet.
1753 // This is useful when the user swipes through from the virtual key area
1754 // into the main display surface.
1755 mCurrentVirtualKey.down = false;
1756 if (!mCurrentVirtualKey.ignored) {
1757#if DEBUG_VIRTUAL_KEYS
1758 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1759 mCurrentVirtualKey.scanCode);
1760#endif
1761 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1762 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1763 AKEY_EVENT_FLAG_CANCELED);
1764 }
1765 }
1766
1767 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1768 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1769 // Pointer just went down. Check for virtual key press or off-screen touches.
1770 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1771 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001772 // Exclude unscaled device for inside surface checking.
1773 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001774 // If exactly one pointer went down, check for virtual key hit.
1775 // Otherwise we will drop the entire stroke.
1776 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1777 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1778 if (virtualKey) {
1779 mCurrentVirtualKey.down = true;
1780 mCurrentVirtualKey.downTime = when;
1781 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1782 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1783 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001784 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1785 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001786
1787 if (!mCurrentVirtualKey.ignored) {
1788#if DEBUG_VIRTUAL_KEYS
1789 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1790 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1791#endif
1792 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1793 AKEY_EVENT_FLAG_FROM_SYSTEM |
1794 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1795 }
1796 }
1797 }
1798 return true;
1799 }
1800 }
1801
1802 // Disable all virtual key touches that happen within a short time interval of the
1803 // most recent touch within the screen area. The idea is to filter out stray
1804 // virtual key presses when interacting with the touch screen.
1805 //
1806 // Problems we're trying to solve:
1807 //
1808 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1809 // virtual key area that is implemented by a separate touch panel and accidentally
1810 // triggers a virtual key.
1811 //
1812 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1813 // area and accidentally triggers a virtual key. This often happens when virtual keys
1814 // are layed out below the screen near to where the on screen keyboard's space bar
1815 // is displayed.
1816 if (mConfig.virtualKeyQuietTime > 0 &&
1817 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001818 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001819 }
1820 return false;
1821}
1822
1823void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1824 int32_t keyEventAction, int32_t keyEventFlags) {
1825 int32_t keyCode = mCurrentVirtualKey.keyCode;
1826 int32_t scanCode = mCurrentVirtualKey.scanCode;
1827 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001828 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001829 policyFlags |= POLICY_FLAG_VIRTUAL;
1830
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06001831 getContext()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
1832 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode,
1833 metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001834}
1835
1836void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1837 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1838 if (!currentIdBits.isEmpty()) {
1839 int32_t metaState = getContext()->getGlobalMetaState();
1840 int32_t buttonState = mCurrentCookedState.buttonState;
1841 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1842 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1843 mCurrentCookedState.cookedPointerData.pointerProperties,
1844 mCurrentCookedState.cookedPointerData.pointerCoords,
1845 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1846 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1847 mCurrentMotionAborted = true;
1848 }
1849}
1850
1851void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1852 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1853 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1854 int32_t metaState = getContext()->getGlobalMetaState();
1855 int32_t buttonState = mCurrentCookedState.buttonState;
1856
1857 if (currentIdBits == lastIdBits) {
1858 if (!currentIdBits.isEmpty()) {
1859 // No pointer id changes so this is a move event.
1860 // The listener takes care of batching moves so we don't have to deal with that here.
1861 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1862 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1863 mCurrentCookedState.cookedPointerData.pointerProperties,
1864 mCurrentCookedState.cookedPointerData.pointerCoords,
1865 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1866 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1867 }
1868 } else {
1869 // There may be pointers going up and pointers going down and pointers moving
1870 // all at the same time.
1871 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1872 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1873 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1874 BitSet32 dispatchedIdBits(lastIdBits.value);
1875
1876 // Update last coordinates of pointers that have moved so that we observe the new
1877 // pointer positions at the same time as other pointers that have just gone up.
1878 bool moveNeeded =
1879 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1880 mCurrentCookedState.cookedPointerData.pointerCoords,
1881 mCurrentCookedState.cookedPointerData.idToIndex,
1882 mLastCookedState.cookedPointerData.pointerProperties,
1883 mLastCookedState.cookedPointerData.pointerCoords,
1884 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1885 if (buttonState != mLastCookedState.buttonState) {
1886 moveNeeded = true;
1887 }
1888
1889 // Dispatch pointer up events.
1890 while (!upIdBits.isEmpty()) {
1891 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001892 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1893 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1894 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001895 mLastCookedState.cookedPointerData.pointerProperties,
1896 mLastCookedState.cookedPointerData.pointerCoords,
1897 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1898 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1899 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001900 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001901 }
1902
1903 // Dispatch move events if any of the remaining pointers moved from their old locations.
1904 // Although applications receive new locations as part of individual pointer up
1905 // events, they do not generally handle them except when presented in a move event.
1906 if (moveNeeded && !moveIdBits.isEmpty()) {
1907 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1908 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1909 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1910 mCurrentCookedState.cookedPointerData.pointerCoords,
1911 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1912 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1913 }
1914
1915 // Dispatch pointer down events using the new pointer locations.
1916 while (!downIdBits.isEmpty()) {
1917 uint32_t downId = downIdBits.clearFirstMarkedBit();
1918 dispatchedIdBits.markBit(downId);
1919
1920 if (dispatchedIdBits.count() == 1) {
1921 // First pointer is going down. Set down time.
1922 mDownTime = when;
1923 }
1924
1925 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1926 metaState, buttonState, 0,
1927 mCurrentCookedState.cookedPointerData.pointerProperties,
1928 mCurrentCookedState.cookedPointerData.pointerCoords,
1929 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1930 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1931 }
1932 }
1933}
1934
1935void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1936 if (mSentHoverEnter &&
1937 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1938 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1939 int32_t metaState = getContext()->getGlobalMetaState();
1940 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1941 mLastCookedState.buttonState, 0,
1942 mLastCookedState.cookedPointerData.pointerProperties,
1943 mLastCookedState.cookedPointerData.pointerCoords,
1944 mLastCookedState.cookedPointerData.idToIndex,
1945 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1946 mOrientedYPrecision, mDownTime);
1947 mSentHoverEnter = false;
1948 }
1949}
1950
1951void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1952 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1953 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1954 int32_t metaState = getContext()->getGlobalMetaState();
1955 if (!mSentHoverEnter) {
1956 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1957 metaState, mCurrentRawState.buttonState, 0,
1958 mCurrentCookedState.cookedPointerData.pointerProperties,
1959 mCurrentCookedState.cookedPointerData.pointerCoords,
1960 mCurrentCookedState.cookedPointerData.idToIndex,
1961 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1962 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1963 mSentHoverEnter = true;
1964 }
1965
1966 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1967 mCurrentRawState.buttonState, 0,
1968 mCurrentCookedState.cookedPointerData.pointerProperties,
1969 mCurrentCookedState.cookedPointerData.pointerCoords,
1970 mCurrentCookedState.cookedPointerData.idToIndex,
1971 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1972 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1973 }
1974}
1975
1976void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1977 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1978 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1979 const int32_t metaState = getContext()->getGlobalMetaState();
1980 int32_t buttonState = mLastCookedState.buttonState;
1981 while (!releasedButtons.isEmpty()) {
1982 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
1983 buttonState &= ~actionButton;
1984 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1985 actionButton, 0, metaState, buttonState, 0,
1986 mCurrentCookedState.cookedPointerData.pointerProperties,
1987 mCurrentCookedState.cookedPointerData.pointerCoords,
1988 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
1989 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1990 }
1991}
1992
1993void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
1994 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
1995 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
1996 const int32_t metaState = getContext()->getGlobalMetaState();
1997 int32_t buttonState = mLastCookedState.buttonState;
1998 while (!pressedButtons.isEmpty()) {
1999 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2000 buttonState |= actionButton;
2001 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2002 0, metaState, buttonState, 0,
2003 mCurrentCookedState.cookedPointerData.pointerProperties,
2004 mCurrentCookedState.cookedPointerData.pointerCoords,
2005 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2006 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2007 }
2008}
2009
2010const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2011 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2012 return cookedPointerData.touchingIdBits;
2013 }
2014 return cookedPointerData.hoveringIdBits;
2015}
2016
2017void TouchInputMapper::cookPointerData() {
2018 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2019
2020 mCurrentCookedState.cookedPointerData.clear();
2021 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2022 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2023 mCurrentRawState.rawPointerData.hoveringIdBits;
2024 mCurrentCookedState.cookedPointerData.touchingIdBits =
2025 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002026 mCurrentCookedState.cookedPointerData.canceledIdBits =
2027 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002028
2029 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2030 mCurrentCookedState.buttonState = 0;
2031 } else {
2032 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2033 }
2034
2035 // Walk through the the active pointers and map device coordinates onto
2036 // surface coordinates and adjust for display orientation.
2037 for (uint32_t i = 0; i < currentPointerCount; i++) {
2038 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2039
2040 // Size
2041 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2042 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002043 case Calibration::SizeCalibration::GEOMETRIC:
2044 case Calibration::SizeCalibration::DIAMETER:
2045 case Calibration::SizeCalibration::BOX:
2046 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002047 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2048 touchMajor = in.touchMajor;
2049 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2050 toolMajor = in.toolMajor;
2051 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2052 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2053 : in.touchMajor;
2054 } else if (mRawPointerAxes.touchMajor.valid) {
2055 toolMajor = touchMajor = in.touchMajor;
2056 toolMinor = touchMinor =
2057 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2058 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2059 : in.touchMajor;
2060 } else if (mRawPointerAxes.toolMajor.valid) {
2061 touchMajor = toolMajor = in.toolMajor;
2062 touchMinor = toolMinor =
2063 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2064 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2065 : in.toolMajor;
2066 } else {
2067 ALOG_ASSERT(false,
2068 "No touch or tool axes. "
2069 "Size calibration should have been resolved to NONE.");
2070 touchMajor = 0;
2071 touchMinor = 0;
2072 toolMajor = 0;
2073 toolMinor = 0;
2074 size = 0;
2075 }
2076
2077 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2078 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2079 if (touchingCount > 1) {
2080 touchMajor /= touchingCount;
2081 touchMinor /= touchingCount;
2082 toolMajor /= touchingCount;
2083 toolMinor /= touchingCount;
2084 size /= touchingCount;
2085 }
2086 }
2087
Michael Wright227c5542020-07-02 18:30:52 +01002088 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089 touchMajor *= mGeometricScale;
2090 touchMinor *= mGeometricScale;
2091 toolMajor *= mGeometricScale;
2092 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002093 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002094 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2095 touchMinor = touchMajor;
2096 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2097 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002098 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002099 touchMinor = touchMajor;
2100 toolMinor = toolMajor;
2101 }
2102
2103 mCalibration.applySizeScaleAndBias(&touchMajor);
2104 mCalibration.applySizeScaleAndBias(&touchMinor);
2105 mCalibration.applySizeScaleAndBias(&toolMajor);
2106 mCalibration.applySizeScaleAndBias(&toolMinor);
2107 size *= mSizeScale;
2108 break;
2109 default:
2110 touchMajor = 0;
2111 touchMinor = 0;
2112 toolMajor = 0;
2113 toolMinor = 0;
2114 size = 0;
2115 break;
2116 }
2117
2118 // Pressure
2119 float pressure;
2120 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002121 case Calibration::PressureCalibration::PHYSICAL:
2122 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002123 pressure = in.pressure * mPressureScale;
2124 break;
2125 default:
2126 pressure = in.isHovering ? 0 : 1;
2127 break;
2128 }
2129
2130 // Tilt and Orientation
2131 float tilt;
2132 float orientation;
2133 if (mHaveTilt) {
2134 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2135 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2136 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2137 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2138 } else {
2139 tilt = 0;
2140
2141 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002142 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002143 orientation = in.orientation * mOrientationScale;
2144 break;
Michael Wright227c5542020-07-02 18:30:52 +01002145 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002146 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2147 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2148 if (c1 != 0 || c2 != 0) {
2149 orientation = atan2f(c1, c2) * 0.5f;
2150 float confidence = hypotf(c1, c2);
2151 float scale = 1.0f + confidence / 16.0f;
2152 touchMajor *= scale;
2153 touchMinor /= scale;
2154 toolMajor *= scale;
2155 toolMinor /= scale;
2156 } else {
2157 orientation = 0;
2158 }
2159 break;
2160 }
2161 default:
2162 orientation = 0;
2163 }
2164 }
2165
2166 // Distance
2167 float distance;
2168 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002169 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170 distance = in.distance * mDistanceScale;
2171 break;
2172 default:
2173 distance = 0;
2174 }
2175
2176 // Coverage
2177 int32_t rawLeft, rawTop, rawRight, rawBottom;
2178 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002179 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002180 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2181 rawRight = in.toolMinor & 0x0000ffff;
2182 rawBottom = in.toolMajor & 0x0000ffff;
2183 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2184 break;
2185 default:
2186 rawLeft = rawTop = rawRight = rawBottom = 0;
2187 break;
2188 }
2189
2190 // Adjust X,Y coords for device calibration
2191 // TODO: Adjust coverage coords?
2192 float xTransformed = in.x, yTransformed = in.y;
2193 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002194 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002195
2196 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002197 float left, top, right, bottom;
2198
2199 switch (mSurfaceOrientation) {
2200 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002201 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2202 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2203 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2204 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2205 orientation -= M_PI_2;
2206 if (mOrientedRanges.haveOrientation &&
2207 orientation < mOrientedRanges.orientation.min) {
2208 orientation +=
2209 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2210 }
2211 break;
2212 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002213 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2214 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2215 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2216 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2217 orientation -= M_PI;
2218 if (mOrientedRanges.haveOrientation &&
2219 orientation < mOrientedRanges.orientation.min) {
2220 orientation +=
2221 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2222 }
2223 break;
2224 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002225 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2226 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2227 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2228 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2229 orientation += M_PI_2;
2230 if (mOrientedRanges.haveOrientation &&
2231 orientation > mOrientedRanges.orientation.max) {
2232 orientation -=
2233 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2234 }
2235 break;
2236 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002237 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2238 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2239 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2240 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2241 break;
2242 }
2243
2244 // Write output coords.
2245 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2246 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002247 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2248 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002249 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2250 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2251 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2252 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2253 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2254 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2255 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002256 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002257 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2258 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2259 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2260 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2261 } else {
2262 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2263 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2264 }
2265
Chris Ye364fdb52020-08-05 15:07:56 -07002266 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002267 uint32_t id = in.id;
2268 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2269 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2270 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2271 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2272 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2273 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2274 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2275 }
2276
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002277 // Write output properties.
2278 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002279 properties.clear();
2280 properties.id = id;
2281 properties.toolType = in.toolType;
2282
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002283 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002284 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002285 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002286 }
2287}
2288
2289void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2290 PointerUsage pointerUsage) {
2291 if (pointerUsage != mPointerUsage) {
2292 abortPointerUsage(when, policyFlags);
2293 mPointerUsage = pointerUsage;
2294 }
2295
2296 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002297 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002298 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2299 break;
Michael Wright227c5542020-07-02 18:30:52 +01002300 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002301 dispatchPointerStylus(when, policyFlags);
2302 break;
Michael Wright227c5542020-07-02 18:30:52 +01002303 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002304 dispatchPointerMouse(when, policyFlags);
2305 break;
Michael Wright227c5542020-07-02 18:30:52 +01002306 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002307 break;
2308 }
2309}
2310
2311void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2312 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002313 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002314 abortPointerGestures(when, policyFlags);
2315 break;
Michael Wright227c5542020-07-02 18:30:52 +01002316 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317 abortPointerStylus(when, policyFlags);
2318 break;
Michael Wright227c5542020-07-02 18:30:52 +01002319 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 abortPointerMouse(when, policyFlags);
2321 break;
Michael Wright227c5542020-07-02 18:30:52 +01002322 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323 break;
2324 }
2325
Michael Wright227c5542020-07-02 18:30:52 +01002326 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002327}
2328
2329void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2330 // Update current gesture coordinates.
2331 bool cancelPreviousGesture, finishPreviousGesture;
2332 bool sendEvents =
2333 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2334 if (!sendEvents) {
2335 return;
2336 }
2337 if (finishPreviousGesture) {
2338 cancelPreviousGesture = false;
2339 }
2340
2341 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002342 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002343 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 if (finishPreviousGesture || cancelPreviousGesture) {
2345 mPointerController->clearSpots();
2346 }
2347
Michael Wright227c5542020-07-02 18:30:52 +01002348 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2350 mPointerGesture.currentGestureIdToIndex,
2351 mPointerGesture.currentGestureIdBits,
2352 mPointerController->getDisplayId());
2353 }
2354 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002355 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 }
2357
2358 // Show or hide the pointer if needed.
2359 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002360 case PointerGesture::Mode::NEUTRAL:
2361 case PointerGesture::Mode::QUIET:
2362 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2363 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002364 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002365 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 }
2367 break;
Michael Wright227c5542020-07-02 18:30:52 +01002368 case PointerGesture::Mode::TAP:
2369 case PointerGesture::Mode::TAP_DRAG:
2370 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2371 case PointerGesture::Mode::HOVER:
2372 case PointerGesture::Mode::PRESS:
2373 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 // Unfade the pointer when the current gesture manipulates the
2375 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002376 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 break;
Michael Wright227c5542020-07-02 18:30:52 +01002378 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 // Fade the pointer when the current gesture manipulates a different
2380 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002381 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002382 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002384 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 }
2386 break;
2387 }
2388
2389 // Send events!
2390 int32_t metaState = getContext()->getGlobalMetaState();
2391 int32_t buttonState = mCurrentCookedState.buttonState;
2392
2393 // Update last coordinates of pointers that have moved so that we observe the new
2394 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002395 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2396 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2397 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2398 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2399 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2400 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002401 bool moveNeeded = false;
2402 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2403 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2404 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2405 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2406 mPointerGesture.lastGestureIdBits.value);
2407 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2408 mPointerGesture.currentGestureCoords,
2409 mPointerGesture.currentGestureIdToIndex,
2410 mPointerGesture.lastGestureProperties,
2411 mPointerGesture.lastGestureCoords,
2412 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2413 if (buttonState != mLastCookedState.buttonState) {
2414 moveNeeded = true;
2415 }
2416 }
2417
2418 // Send motion events for all pointers that went up or were canceled.
2419 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2420 if (!dispatchedGestureIdBits.isEmpty()) {
2421 if (cancelPreviousGesture) {
2422 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2423 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2424 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2425 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2426 mPointerGesture.downTime);
2427
2428 dispatchedGestureIdBits.clear();
2429 } else {
2430 BitSet32 upGestureIdBits;
2431 if (finishPreviousGesture) {
2432 upGestureIdBits = dispatchedGestureIdBits;
2433 } else {
2434 upGestureIdBits.value =
2435 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2436 }
2437 while (!upGestureIdBits.isEmpty()) {
2438 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2439
2440 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2441 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2442 mPointerGesture.lastGestureProperties,
2443 mPointerGesture.lastGestureCoords,
2444 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2445 0, mPointerGesture.downTime);
2446
2447 dispatchedGestureIdBits.clearBit(id);
2448 }
2449 }
2450 }
2451
2452 // Send motion events for all pointers that moved.
2453 if (moveNeeded) {
2454 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2455 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2456 mPointerGesture.currentGestureProperties,
2457 mPointerGesture.currentGestureCoords,
2458 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2459 mPointerGesture.downTime);
2460 }
2461
2462 // Send motion events for all pointers that went down.
2463 if (down) {
2464 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2465 ~dispatchedGestureIdBits.value);
2466 while (!downGestureIdBits.isEmpty()) {
2467 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2468 dispatchedGestureIdBits.markBit(id);
2469
2470 if (dispatchedGestureIdBits.count() == 1) {
2471 mPointerGesture.downTime = when;
2472 }
2473
2474 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2475 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2476 mPointerGesture.currentGestureCoords,
2477 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2478 0, mPointerGesture.downTime);
2479 }
2480 }
2481
2482 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002483 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002484 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2485 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2486 mPointerGesture.currentGestureProperties,
2487 mPointerGesture.currentGestureCoords,
2488 mPointerGesture.currentGestureIdToIndex,
2489 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2490 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2491 // Synthesize a hover move event after all pointers go up to indicate that
2492 // the pointer is hovering again even if the user is not currently touching
2493 // the touch pad. This ensures that a view will receive a fresh hover enter
2494 // event after a tap.
2495 float x, y;
2496 mPointerController->getPosition(&x, &y);
2497
2498 PointerProperties pointerProperties;
2499 pointerProperties.clear();
2500 pointerProperties.id = 0;
2501 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2502
2503 PointerCoords pointerCoords;
2504 pointerCoords.clear();
2505 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2506 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2507
2508 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06002509 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
2510 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState,
2511 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
2512 &pointerProperties, &pointerCoords, 0, 0, x, y,
2513 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 }
2515
2516 // Update state.
2517 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2518 if (!down) {
2519 mPointerGesture.lastGestureIdBits.clear();
2520 } else {
2521 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2522 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2523 uint32_t id = idBits.clearFirstMarkedBit();
2524 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2525 mPointerGesture.lastGestureProperties[index].copyFrom(
2526 mPointerGesture.currentGestureProperties[index]);
2527 mPointerGesture.lastGestureCoords[index].copyFrom(
2528 mPointerGesture.currentGestureCoords[index]);
2529 mPointerGesture.lastGestureIdToIndex[id] = index;
2530 }
2531 }
2532}
2533
2534void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2535 // Cancel previously dispatches pointers.
2536 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2537 int32_t metaState = getContext()->getGlobalMetaState();
2538 int32_t buttonState = mCurrentRawState.buttonState;
2539 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2540 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2541 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2542 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2543 0, 0, mPointerGesture.downTime);
2544 }
2545
2546 // Reset the current pointer gesture.
2547 mPointerGesture.reset();
2548 mPointerVelocityControl.reset();
2549
2550 // Remove any current spots.
2551 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002552 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 mPointerController->clearSpots();
2554 }
2555}
2556
2557bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2558 bool* outFinishPreviousGesture, bool isTimeout) {
2559 *outCancelPreviousGesture = false;
2560 *outFinishPreviousGesture = false;
2561
2562 // Handle TAP timeout.
2563 if (isTimeout) {
2564#if DEBUG_GESTURES
2565 ALOGD("Gestures: Processing timeout");
2566#endif
2567
Michael Wright227c5542020-07-02 18:30:52 +01002568 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002569 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2570 // The tap/drag timeout has not yet expired.
2571 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2572 mConfig.pointerGestureTapDragInterval);
2573 } else {
2574 // The tap is finished.
2575#if DEBUG_GESTURES
2576 ALOGD("Gestures: TAP finished");
2577#endif
2578 *outFinishPreviousGesture = true;
2579
2580 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002581 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002582 mPointerGesture.currentGestureIdBits.clear();
2583
2584 mPointerVelocityControl.reset();
2585 return true;
2586 }
2587 }
2588
2589 // We did not handle this timeout.
2590 return false;
2591 }
2592
2593 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2594 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2595
2596 // Update the velocity tracker.
2597 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002598 std::vector<VelocityTracker::Position> positions;
2599 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002600 uint32_t id = idBits.clearFirstMarkedBit();
2601 const RawPointerData::Pointer& pointer =
2602 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002603 float x = pointer.x * mPointerXMovementScale;
2604 float y = pointer.y * mPointerYMovementScale;
2605 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002606 }
2607 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2608 positions);
2609 }
2610
2611 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2612 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002613 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2614 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2615 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002616 mPointerGesture.resetTap();
2617 }
2618
2619 // Pick a new active touch id if needed.
2620 // Choose an arbitrary pointer that just went down, if there is one.
2621 // Otherwise choose an arbitrary remaining pointer.
2622 // This guarantees we always have an active touch id when there is at least one pointer.
2623 // We keep the same active touch id for as long as possible.
2624 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2625 int32_t activeTouchId = lastActiveTouchId;
2626 if (activeTouchId < 0) {
2627 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2628 activeTouchId = mPointerGesture.activeTouchId =
2629 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2630 mPointerGesture.firstTouchTime = when;
2631 }
2632 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2633 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2634 activeTouchId = mPointerGesture.activeTouchId =
2635 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2636 } else {
2637 activeTouchId = mPointerGesture.activeTouchId = -1;
2638 }
2639 }
2640
2641 // Determine whether we are in quiet time.
2642 bool isQuietTime = false;
2643 if (activeTouchId < 0) {
2644 mPointerGesture.resetQuietTime();
2645 } else {
2646 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2647 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002648 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2649 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2650 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002651 currentFingerCount < 2) {
2652 // Enter quiet time when exiting swipe or freeform state.
2653 // This is to prevent accidentally entering the hover state and flinging the
2654 // pointer when finishing a swipe and there is still one pointer left onscreen.
2655 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002656 } else if (mPointerGesture.lastGestureMode ==
2657 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002658 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2659 // Enter quiet time when releasing the button and there are still two or more
2660 // fingers down. This may indicate that one finger was used to press the button
2661 // but it has not gone up yet.
2662 isQuietTime = true;
2663 }
2664 if (isQuietTime) {
2665 mPointerGesture.quietTime = when;
2666 }
2667 }
2668 }
2669
2670 // Switch states based on button and pointer state.
2671 if (isQuietTime) {
2672 // Case 1: Quiet time. (QUIET)
2673#if DEBUG_GESTURES
2674 ALOGD("Gestures: QUIET for next %0.3fms",
2675 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2676#endif
Michael Wright227c5542020-07-02 18:30:52 +01002677 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002678 *outFinishPreviousGesture = true;
2679 }
2680
2681 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002682 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002683 mPointerGesture.currentGestureIdBits.clear();
2684
2685 mPointerVelocityControl.reset();
2686 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2687 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2688 // The pointer follows the active touch point.
2689 // Emit DOWN, MOVE, UP events at the pointer location.
2690 //
2691 // Only the active touch matters; other fingers are ignored. This policy helps
2692 // to handle the case where the user places a second finger on the touch pad
2693 // to apply the necessary force to depress an integrated button below the surface.
2694 // We don't want the second finger to be delivered to applications.
2695 //
2696 // For this to work well, we need to make sure to track the pointer that is really
2697 // active. If the user first puts one finger down to click then adds another
2698 // finger to drag then the active pointer should switch to the finger that is
2699 // being dragged.
2700#if DEBUG_GESTURES
2701 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2702 "currentFingerCount=%d",
2703 activeTouchId, currentFingerCount);
2704#endif
2705 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002706 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002707 *outFinishPreviousGesture = true;
2708 mPointerGesture.activeGestureId = 0;
2709 }
2710
2711 // Switch pointers if needed.
2712 // Find the fastest pointer and follow it.
2713 if (activeTouchId >= 0 && currentFingerCount > 1) {
2714 int32_t bestId = -1;
2715 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2716 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2717 uint32_t id = idBits.clearFirstMarkedBit();
2718 float vx, vy;
2719 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2720 float speed = hypotf(vx, vy);
2721 if (speed > bestSpeed) {
2722 bestId = id;
2723 bestSpeed = speed;
2724 }
2725 }
2726 }
2727 if (bestId >= 0 && bestId != activeTouchId) {
2728 mPointerGesture.activeTouchId = activeTouchId = bestId;
2729#if DEBUG_GESTURES
2730 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2731 "bestId=%d, bestSpeed=%0.3f",
2732 bestId, bestSpeed);
2733#endif
2734 }
2735 }
2736
2737 float deltaX = 0, deltaY = 0;
2738 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2739 const RawPointerData::Pointer& currentPointer =
2740 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2741 const RawPointerData::Pointer& lastPointer =
2742 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2743 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2744 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2745
2746 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2747 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2748
2749 // Move the pointer using a relative motion.
2750 // When using spots, the click will occur at the position of the anchor
2751 // spot and all other spots will move there.
2752 mPointerController->move(deltaX, deltaY);
2753 } else {
2754 mPointerVelocityControl.reset();
2755 }
2756
2757 float x, y;
2758 mPointerController->getPosition(&x, &y);
2759
Michael Wright227c5542020-07-02 18:30:52 +01002760 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002761 mPointerGesture.currentGestureIdBits.clear();
2762 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2763 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2764 mPointerGesture.currentGestureProperties[0].clear();
2765 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2766 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2767 mPointerGesture.currentGestureCoords[0].clear();
2768 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2769 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2770 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2771 } else if (currentFingerCount == 0) {
2772 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002773 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002774 *outFinishPreviousGesture = true;
2775 }
2776
2777 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2778 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2779 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002780 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2781 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002782 lastFingerCount == 1) {
2783 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2784 float x, y;
2785 mPointerController->getPosition(&x, &y);
2786 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2787 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2788#if DEBUG_GESTURES
2789 ALOGD("Gestures: TAP");
2790#endif
2791
2792 mPointerGesture.tapUpTime = when;
2793 getContext()->requestTimeoutAtTime(when +
2794 mConfig.pointerGestureTapDragInterval);
2795
2796 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002797 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002798 mPointerGesture.currentGestureIdBits.clear();
2799 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2800 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2801 mPointerGesture.currentGestureProperties[0].clear();
2802 mPointerGesture.currentGestureProperties[0].id =
2803 mPointerGesture.activeGestureId;
2804 mPointerGesture.currentGestureProperties[0].toolType =
2805 AMOTION_EVENT_TOOL_TYPE_FINGER;
2806 mPointerGesture.currentGestureCoords[0].clear();
2807 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2808 mPointerGesture.tapX);
2809 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2810 mPointerGesture.tapY);
2811 mPointerGesture.currentGestureCoords[0]
2812 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2813
2814 tapped = true;
2815 } else {
2816#if DEBUG_GESTURES
2817 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2818 y - mPointerGesture.tapY);
2819#endif
2820 }
2821 } else {
2822#if DEBUG_GESTURES
2823 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2824 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2825 (when - mPointerGesture.tapDownTime) * 0.000001f);
2826 } else {
2827 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2828 }
2829#endif
2830 }
2831 }
2832
2833 mPointerVelocityControl.reset();
2834
2835 if (!tapped) {
2836#if DEBUG_GESTURES
2837 ALOGD("Gestures: NEUTRAL");
2838#endif
2839 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002840 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002841 mPointerGesture.currentGestureIdBits.clear();
2842 }
2843 } else if (currentFingerCount == 1) {
2844 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2845 // The pointer follows the active touch point.
2846 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2847 // When in TAP_DRAG, emit MOVE events at the pointer location.
2848 ALOG_ASSERT(activeTouchId >= 0);
2849
Michael Wright227c5542020-07-02 18:30:52 +01002850 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2851 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002852 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2853 float x, y;
2854 mPointerController->getPosition(&x, &y);
2855 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2856 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002857 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002858 } else {
2859#if DEBUG_GESTURES
2860 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2861 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2862#endif
2863 }
2864 } else {
2865#if DEBUG_GESTURES
2866 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2867 (when - mPointerGesture.tapUpTime) * 0.000001f);
2868#endif
2869 }
Michael Wright227c5542020-07-02 18:30:52 +01002870 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2871 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 }
2873
2874 float deltaX = 0, deltaY = 0;
2875 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2876 const RawPointerData::Pointer& currentPointer =
2877 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2878 const RawPointerData::Pointer& lastPointer =
2879 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2880 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2881 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2882
2883 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2884 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2885
2886 // Move the pointer using a relative motion.
2887 // When using spots, the hover or drag will occur at the position of the anchor spot.
2888 mPointerController->move(deltaX, deltaY);
2889 } else {
2890 mPointerVelocityControl.reset();
2891 }
2892
2893 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002894 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895#if DEBUG_GESTURES
2896 ALOGD("Gestures: TAP_DRAG");
2897#endif
2898 down = true;
2899 } else {
2900#if DEBUG_GESTURES
2901 ALOGD("Gestures: HOVER");
2902#endif
Michael Wright227c5542020-07-02 18:30:52 +01002903 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002904 *outFinishPreviousGesture = true;
2905 }
2906 mPointerGesture.activeGestureId = 0;
2907 down = false;
2908 }
2909
2910 float x, y;
2911 mPointerController->getPosition(&x, &y);
2912
2913 mPointerGesture.currentGestureIdBits.clear();
2914 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2915 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2916 mPointerGesture.currentGestureProperties[0].clear();
2917 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2918 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2919 mPointerGesture.currentGestureCoords[0].clear();
2920 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2921 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2922 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2923 down ? 1.0f : 0.0f);
2924
2925 if (lastFingerCount == 0 && currentFingerCount != 0) {
2926 mPointerGesture.resetTap();
2927 mPointerGesture.tapDownTime = when;
2928 mPointerGesture.tapX = x;
2929 mPointerGesture.tapY = y;
2930 }
2931 } else {
2932 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2933 // We need to provide feedback for each finger that goes down so we cannot wait
2934 // for the fingers to move before deciding what to do.
2935 //
2936 // The ambiguous case is deciding what to do when there are two fingers down but they
2937 // have not moved enough to determine whether they are part of a drag or part of a
2938 // freeform gesture, or just a press or long-press at the pointer location.
2939 //
2940 // When there are two fingers we start with the PRESS hypothesis and we generate a
2941 // down at the pointer location.
2942 //
2943 // When the two fingers move enough or when additional fingers are added, we make
2944 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2945 ALOG_ASSERT(activeTouchId >= 0);
2946
2947 bool settled = when >=
2948 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002949 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2950 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2951 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 *outFinishPreviousGesture = true;
2953 } else if (!settled && currentFingerCount > lastFingerCount) {
2954 // Additional pointers have gone down but not yet settled.
2955 // Reset the gesture.
2956#if DEBUG_GESTURES
2957 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2958 "settle time remaining %0.3fms",
2959 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2960 when) * 0.000001f);
2961#endif
2962 *outCancelPreviousGesture = true;
2963 } else {
2964 // Continue previous gesture.
2965 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2966 }
2967
2968 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002969 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 mPointerGesture.activeGestureId = 0;
2971 mPointerGesture.referenceIdBits.clear();
2972 mPointerVelocityControl.reset();
2973
2974 // Use the centroid and pointer location as the reference points for the gesture.
2975#if DEBUG_GESTURES
2976 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2977 "settle time remaining %0.3fms",
2978 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2979 when) * 0.000001f);
2980#endif
2981 mCurrentRawState.rawPointerData
2982 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
2983 &mPointerGesture.referenceTouchY);
2984 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
2985 &mPointerGesture.referenceGestureY);
2986 }
2987
2988 // Clear the reference deltas for fingers not yet included in the reference calculation.
2989 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
2990 ~mPointerGesture.referenceIdBits.value);
2991 !idBits.isEmpty();) {
2992 uint32_t id = idBits.clearFirstMarkedBit();
2993 mPointerGesture.referenceDeltas[id].dx = 0;
2994 mPointerGesture.referenceDeltas[id].dy = 0;
2995 }
2996 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
2997
2998 // Add delta for all fingers and calculate a common movement delta.
2999 float commonDeltaX = 0, commonDeltaY = 0;
3000 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3001 mCurrentCookedState.fingerIdBits.value);
3002 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3003 bool first = (idBits == commonIdBits);
3004 uint32_t id = idBits.clearFirstMarkedBit();
3005 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3006 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3007 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3008 delta.dx += cpd.x - lpd.x;
3009 delta.dy += cpd.y - lpd.y;
3010
3011 if (first) {
3012 commonDeltaX = delta.dx;
3013 commonDeltaY = delta.dy;
3014 } else {
3015 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3016 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3017 }
3018 }
3019
3020 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003021 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003022 float dist[MAX_POINTER_ID + 1];
3023 int32_t distOverThreshold = 0;
3024 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3025 uint32_t id = idBits.clearFirstMarkedBit();
3026 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3027 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3028 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3029 distOverThreshold += 1;
3030 }
3031 }
3032
3033 // Only transition when at least two pointers have moved further than
3034 // the minimum distance threshold.
3035 if (distOverThreshold >= 2) {
3036 if (currentFingerCount > 2) {
3037 // There are more than two pointers, switch to FREEFORM.
3038#if DEBUG_GESTURES
3039 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3040 currentFingerCount);
3041#endif
3042 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003043 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003044 } else {
3045 // There are exactly two pointers.
3046 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3047 uint32_t id1 = idBits.clearFirstMarkedBit();
3048 uint32_t id2 = idBits.firstMarkedBit();
3049 const RawPointerData::Pointer& p1 =
3050 mCurrentRawState.rawPointerData.pointerForId(id1);
3051 const RawPointerData::Pointer& p2 =
3052 mCurrentRawState.rawPointerData.pointerForId(id2);
3053 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3054 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3055 // There are two pointers but they are too far apart for a SWIPE,
3056 // switch to FREEFORM.
3057#if DEBUG_GESTURES
3058 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3059 mutualDistance, mPointerGestureMaxSwipeWidth);
3060#endif
3061 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003062 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003063 } else {
3064 // There are two pointers. Wait for both pointers to start moving
3065 // before deciding whether this is a SWIPE or FREEFORM gesture.
3066 float dist1 = dist[id1];
3067 float dist2 = dist[id2];
3068 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3069 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3070 // Calculate the dot product of the displacement vectors.
3071 // When the vectors are oriented in approximately the same direction,
3072 // the angle betweeen them is near zero and the cosine of the angle
3073 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3074 // mag(v2).
3075 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3076 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3077 float dx1 = delta1.dx * mPointerXZoomScale;
3078 float dy1 = delta1.dy * mPointerYZoomScale;
3079 float dx2 = delta2.dx * mPointerXZoomScale;
3080 float dy2 = delta2.dy * mPointerYZoomScale;
3081 float dot = dx1 * dx2 + dy1 * dy2;
3082 float cosine = dot / (dist1 * dist2); // denominator always > 0
3083 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3084 // Pointers are moving in the same direction. Switch to SWIPE.
3085#if DEBUG_GESTURES
3086 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3087 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3088 "cosine %0.3f >= %0.3f",
3089 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3090 mConfig.pointerGestureMultitouchMinDistance, cosine,
3091 mConfig.pointerGestureSwipeTransitionAngleCosine);
3092#endif
Michael Wright227c5542020-07-02 18:30:52 +01003093 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003094 } else {
3095 // Pointers are moving in different directions. Switch to FREEFORM.
3096#if DEBUG_GESTURES
3097 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3098 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3099 "cosine %0.3f < %0.3f",
3100 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3101 mConfig.pointerGestureMultitouchMinDistance, cosine,
3102 mConfig.pointerGestureSwipeTransitionAngleCosine);
3103#endif
3104 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003105 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003106 }
3107 }
3108 }
3109 }
3110 }
Michael Wright227c5542020-07-02 18:30:52 +01003111 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003112 // Switch from SWIPE to FREEFORM if additional pointers go down.
3113 // Cancel previous gesture.
3114 if (currentFingerCount > 2) {
3115#if DEBUG_GESTURES
3116 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3117 currentFingerCount);
3118#endif
3119 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003120 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003121 }
3122 }
3123
3124 // Move the reference points based on the overall group motion of the fingers
3125 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003126 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003127 (commonDeltaX || commonDeltaY)) {
3128 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3129 uint32_t id = idBits.clearFirstMarkedBit();
3130 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3131 delta.dx = 0;
3132 delta.dy = 0;
3133 }
3134
3135 mPointerGesture.referenceTouchX += commonDeltaX;
3136 mPointerGesture.referenceTouchY += commonDeltaY;
3137
3138 commonDeltaX *= mPointerXMovementScale;
3139 commonDeltaY *= mPointerYMovementScale;
3140
3141 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3142 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3143
3144 mPointerGesture.referenceGestureX += commonDeltaX;
3145 mPointerGesture.referenceGestureY += commonDeltaY;
3146 }
3147
3148 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003149 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3150 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003151 // PRESS or SWIPE mode.
3152#if DEBUG_GESTURES
3153 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3154 "activeGestureId=%d, currentTouchPointerCount=%d",
3155 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3156#endif
3157 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3158
3159 mPointerGesture.currentGestureIdBits.clear();
3160 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3161 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3162 mPointerGesture.currentGestureProperties[0].clear();
3163 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3164 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3165 mPointerGesture.currentGestureCoords[0].clear();
3166 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3167 mPointerGesture.referenceGestureX);
3168 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3169 mPointerGesture.referenceGestureY);
3170 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003171 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003172 // FREEFORM mode.
3173#if DEBUG_GESTURES
3174 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3175 "activeGestureId=%d, currentTouchPointerCount=%d",
3176 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3177#endif
3178 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3179
3180 mPointerGesture.currentGestureIdBits.clear();
3181
3182 BitSet32 mappedTouchIdBits;
3183 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003184 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003185 // Initially, assign the active gesture id to the active touch point
3186 // if there is one. No other touch id bits are mapped yet.
3187 if (!*outCancelPreviousGesture) {
3188 mappedTouchIdBits.markBit(activeTouchId);
3189 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3190 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3191 mPointerGesture.activeGestureId;
3192 } else {
3193 mPointerGesture.activeGestureId = -1;
3194 }
3195 } else {
3196 // Otherwise, assume we mapped all touches from the previous frame.
3197 // Reuse all mappings that are still applicable.
3198 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3199 mCurrentCookedState.fingerIdBits.value;
3200 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3201
3202 // Check whether we need to choose a new active gesture id because the
3203 // current went went up.
3204 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3205 ~mCurrentCookedState.fingerIdBits.value);
3206 !upTouchIdBits.isEmpty();) {
3207 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3208 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3209 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3210 mPointerGesture.activeGestureId = -1;
3211 break;
3212 }
3213 }
3214 }
3215
3216#if DEBUG_GESTURES
3217 ALOGD("Gestures: FREEFORM follow up "
3218 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3219 "activeGestureId=%d",
3220 mappedTouchIdBits.value, usedGestureIdBits.value,
3221 mPointerGesture.activeGestureId);
3222#endif
3223
3224 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3225 for (uint32_t i = 0; i < currentFingerCount; i++) {
3226 uint32_t touchId = idBits.clearFirstMarkedBit();
3227 uint32_t gestureId;
3228 if (!mappedTouchIdBits.hasBit(touchId)) {
3229 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3230 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3231#if DEBUG_GESTURES
3232 ALOGD("Gestures: FREEFORM "
3233 "new mapping for touch id %d -> gesture id %d",
3234 touchId, gestureId);
3235#endif
3236 } else {
3237 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3238#if DEBUG_GESTURES
3239 ALOGD("Gestures: FREEFORM "
3240 "existing mapping for touch id %d -> gesture id %d",
3241 touchId, gestureId);
3242#endif
3243 }
3244 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3245 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3246
3247 const RawPointerData::Pointer& pointer =
3248 mCurrentRawState.rawPointerData.pointerForId(touchId);
3249 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3250 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3251 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3252
3253 mPointerGesture.currentGestureProperties[i].clear();
3254 mPointerGesture.currentGestureProperties[i].id = gestureId;
3255 mPointerGesture.currentGestureProperties[i].toolType =
3256 AMOTION_EVENT_TOOL_TYPE_FINGER;
3257 mPointerGesture.currentGestureCoords[i].clear();
3258 mPointerGesture.currentGestureCoords[i]
3259 .setAxisValue(AMOTION_EVENT_AXIS_X,
3260 mPointerGesture.referenceGestureX + deltaX);
3261 mPointerGesture.currentGestureCoords[i]
3262 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3263 mPointerGesture.referenceGestureY + deltaY);
3264 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3265 1.0f);
3266 }
3267
3268 if (mPointerGesture.activeGestureId < 0) {
3269 mPointerGesture.activeGestureId =
3270 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3271#if DEBUG_GESTURES
3272 ALOGD("Gestures: FREEFORM new "
3273 "activeGestureId=%d",
3274 mPointerGesture.activeGestureId);
3275#endif
3276 }
3277 }
3278 }
3279
3280 mPointerController->setButtonState(mCurrentRawState.buttonState);
3281
3282#if DEBUG_GESTURES
3283 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3284 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3285 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3286 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3287 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3288 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3289 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3290 uint32_t id = idBits.clearFirstMarkedBit();
3291 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3292 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3293 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3294 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3295 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3296 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3297 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3298 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3299 }
3300 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3301 uint32_t id = idBits.clearFirstMarkedBit();
3302 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3303 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3304 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3305 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3306 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3307 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3308 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3309 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3310 }
3311#endif
3312 return true;
3313}
3314
3315void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3316 mPointerSimple.currentCoords.clear();
3317 mPointerSimple.currentProperties.clear();
3318
3319 bool down, hovering;
3320 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3321 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3322 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3323 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3324 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3325 mPointerController->setPosition(x, y);
3326
3327 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3328 down = !hovering;
3329
3330 mPointerController->getPosition(&x, &y);
3331 mPointerSimple.currentCoords.copyFrom(
3332 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3333 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3334 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3335 mPointerSimple.currentProperties.id = 0;
3336 mPointerSimple.currentProperties.toolType =
3337 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3338 } else {
3339 down = false;
3340 hovering = false;
3341 }
3342
3343 dispatchPointerSimple(when, policyFlags, down, hovering);
3344}
3345
3346void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3347 abortPointerSimple(when, policyFlags);
3348}
3349
3350void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3351 mPointerSimple.currentCoords.clear();
3352 mPointerSimple.currentProperties.clear();
3353
3354 bool down, hovering;
3355 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3356 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3357 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3358 float deltaX = 0, deltaY = 0;
3359 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3360 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3361 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3362 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3363 mPointerXMovementScale;
3364 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3365 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3366 mPointerYMovementScale;
3367
3368 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3369 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3370
3371 mPointerController->move(deltaX, deltaY);
3372 } else {
3373 mPointerVelocityControl.reset();
3374 }
3375
3376 down = isPointerDown(mCurrentRawState.buttonState);
3377 hovering = !down;
3378
3379 float x, y;
3380 mPointerController->getPosition(&x, &y);
3381 mPointerSimple.currentCoords.copyFrom(
3382 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3383 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3384 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3385 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3386 hovering ? 0.0f : 1.0f);
3387 mPointerSimple.currentProperties.id = 0;
3388 mPointerSimple.currentProperties.toolType =
3389 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3390 } else {
3391 mPointerVelocityControl.reset();
3392
3393 down = false;
3394 hovering = false;
3395 }
3396
3397 dispatchPointerSimple(when, policyFlags, down, hovering);
3398}
3399
3400void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3401 abortPointerSimple(when, policyFlags);
3402
3403 mPointerVelocityControl.reset();
3404}
3405
3406void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3407 bool hovering) {
3408 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003409
3410 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003411 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003412 mPointerController->clearSpots();
3413 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003414 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003415 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003416 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003417 }
Garfield Tan9514d782020-11-10 16:37:23 -08003418 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003419
3420 float xCursorPosition;
3421 float yCursorPosition;
3422 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3423
3424 if (mPointerSimple.down && !down) {
3425 mPointerSimple.down = false;
3426
3427 // Send up.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003428 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3429 AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
3430 mLastRawState.buttonState, MotionClassification::NONE,
3431 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3432 &mPointerSimple.lastCoords, mOrientedXPrecision,
3433 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3434 mPointerSimple.downTime,
3435 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003436 }
3437
3438 if (mPointerSimple.hovering && !hovering) {
3439 mPointerSimple.hovering = false;
3440
3441 // Send hover exit.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003442 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3443 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3444 mLastRawState.buttonState, MotionClassification::NONE,
3445 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3446 &mPointerSimple.lastCoords, mOrientedXPrecision,
3447 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3448 mPointerSimple.downTime,
3449 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003450 }
3451
3452 if (down) {
3453 if (!mPointerSimple.down) {
3454 mPointerSimple.down = true;
3455 mPointerSimple.downTime = when;
3456
3457 // Send down.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003458 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3459 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3460 mCurrentRawState.buttonState, MotionClassification::NONE,
3461 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3462 &mPointerSimple.currentProperties,
3463 &mPointerSimple.currentCoords, mOrientedXPrecision,
3464 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3465 mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003466 }
3467
3468 // Send move.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003469 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3470 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
3471 mCurrentRawState.buttonState, MotionClassification::NONE,
3472 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3473 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3474 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3475 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003476 }
3477
3478 if (hovering) {
3479 if (!mPointerSimple.hovering) {
3480 mPointerSimple.hovering = true;
3481
3482 // Send hover enter.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003483 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3484 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3485 mCurrentRawState.buttonState, MotionClassification::NONE,
3486 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3487 &mPointerSimple.currentProperties,
3488 &mPointerSimple.currentCoords, mOrientedXPrecision,
3489 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3490 mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003491 }
3492
3493 // Send hover move.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003494 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3495 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3496 mCurrentRawState.buttonState, MotionClassification::NONE,
3497 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3498 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3499 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3500 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003501 }
3502
3503 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3504 float vscroll = mCurrentRawState.rawVScroll;
3505 float hscroll = mCurrentRawState.rawHScroll;
3506 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3507 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3508
3509 // Send scroll.
3510 PointerCoords pointerCoords;
3511 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3512 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3513 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3514
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003515 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3516 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
3517 mCurrentRawState.buttonState, MotionClassification::NONE,
3518 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3519 &mPointerSimple.currentProperties, &pointerCoords,
3520 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3521 yCursorPosition, mPointerSimple.downTime,
3522 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003523 }
3524
3525 // Save state.
3526 if (down || hovering) {
3527 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3528 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3529 } else {
3530 mPointerSimple.reset();
3531 }
3532}
3533
3534void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3535 mPointerSimple.currentCoords.clear();
3536 mPointerSimple.currentProperties.clear();
3537
3538 dispatchPointerSimple(when, policyFlags, false, false);
3539}
3540
3541void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3542 int32_t action, int32_t actionButton, int32_t flags,
3543 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3544 const PointerProperties* properties,
3545 const PointerCoords* coords, const uint32_t* idToIndex,
3546 BitSet32 idBits, int32_t changedId, float xPrecision,
3547 float yPrecision, nsecs_t downTime) {
3548 PointerCoords pointerCoords[MAX_POINTERS];
3549 PointerProperties pointerProperties[MAX_POINTERS];
3550 uint32_t pointerCount = 0;
3551 while (!idBits.isEmpty()) {
3552 uint32_t id = idBits.clearFirstMarkedBit();
3553 uint32_t index = idToIndex[id];
3554 pointerProperties[pointerCount].copyFrom(properties[index]);
3555 pointerCoords[pointerCount].copyFrom(coords[index]);
3556
3557 if (changedId >= 0 && id == uint32_t(changedId)) {
3558 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3559 }
3560
3561 pointerCount += 1;
3562 }
3563
3564 ALOG_ASSERT(pointerCount != 0);
3565
3566 if (changedId >= 0 && pointerCount == 1) {
3567 // Replace initial down and final up action.
3568 // We can compare the action without masking off the changed pointer index
3569 // because we know the index is 0.
3570 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3571 action = AMOTION_EVENT_ACTION_DOWN;
3572 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003573 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3574 action = AMOTION_EVENT_ACTION_CANCEL;
3575 } else {
3576 action = AMOTION_EVENT_ACTION_UP;
3577 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003578 } else {
3579 // Can't happen.
3580 ALOG_ASSERT(false);
3581 }
3582 }
3583 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3584 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003585 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003586 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3587 }
3588 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3589 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003590 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003591 std::for_each(frames.begin(), frames.end(),
3592 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003593 getContext()->notifyMotion(when, deviceId, source, displayId, policyFlags, action, actionButton,
3594 flags, metaState, buttonState, MotionClassification::NONE, edgeFlags,
3595 pointerCount, pointerProperties, pointerCoords, xPrecision,
3596 yPrecision, xCursorPosition, yCursorPosition, downTime,
3597 std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598}
3599
3600bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3601 const PointerCoords* inCoords,
3602 const uint32_t* inIdToIndex,
3603 PointerProperties* outProperties,
3604 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3605 BitSet32 idBits) const {
3606 bool changed = false;
3607 while (!idBits.isEmpty()) {
3608 uint32_t id = idBits.clearFirstMarkedBit();
3609 uint32_t inIndex = inIdToIndex[id];
3610 uint32_t outIndex = outIdToIndex[id];
3611
3612 const PointerProperties& curInProperties = inProperties[inIndex];
3613 const PointerCoords& curInCoords = inCoords[inIndex];
3614 PointerProperties& curOutProperties = outProperties[outIndex];
3615 PointerCoords& curOutCoords = outCoords[outIndex];
3616
3617 if (curInProperties != curOutProperties) {
3618 curOutProperties.copyFrom(curInProperties);
3619 changed = true;
3620 }
3621
3622 if (curInCoords != curOutCoords) {
3623 curOutCoords.copyFrom(curInCoords);
3624 changed = true;
3625 }
3626 }
3627 return changed;
3628}
3629
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003630void TouchInputMapper::cancelTouch(nsecs_t when) {
3631 abortPointerUsage(when, 0 /*policyFlags*/);
3632 abortTouches(when, 0 /* policyFlags*/);
3633}
3634
Arthur Hung4197f6b2020-03-16 15:39:59 +08003635// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003636void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003637 // Scale to surface coordinate.
3638 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3639 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3640
arthurhunga36b28e2020-12-29 20:28:15 +08003641 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3642 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3643
Arthur Hung4197f6b2020-03-16 15:39:59 +08003644 // Rotate to surface coordinate.
3645 // 0 - no swap and reverse.
3646 // 90 - swap x/y and reverse y.
3647 // 180 - reverse x, y.
3648 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003649 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003650 case DISPLAY_ORIENTATION_0:
3651 x = xScaled + mXTranslate;
3652 y = yScaled + mYTranslate;
3653 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003654 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003655 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003656 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003657 break;
3658 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003659 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3660 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003661 break;
3662 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003663 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003664 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003665 break;
3666 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003667 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003668 }
3669}
3670
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003671bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003672 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3673 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3674
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003675 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003676 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003677 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003678 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003679}
3680
3681const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3682 for (const VirtualKey& virtualKey : mVirtualKeys) {
3683#if DEBUG_VIRTUAL_KEYS
3684 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3685 "left=%d, top=%d, right=%d, bottom=%d",
3686 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3687 virtualKey.hitRight, virtualKey.hitBottom);
3688#endif
3689
3690 if (virtualKey.isHit(x, y)) {
3691 return &virtualKey;
3692 }
3693 }
3694
3695 return nullptr;
3696}
3697
3698void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3699 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3700 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3701
3702 current->rawPointerData.clearIdBits();
3703
3704 if (currentPointerCount == 0) {
3705 // No pointers to assign.
3706 return;
3707 }
3708
3709 if (lastPointerCount == 0) {
3710 // All pointers are new.
3711 for (uint32_t i = 0; i < currentPointerCount; i++) {
3712 uint32_t id = i;
3713 current->rawPointerData.pointers[i].id = id;
3714 current->rawPointerData.idToIndex[id] = i;
3715 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3716 }
3717 return;
3718 }
3719
3720 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3721 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3722 // Only one pointer and no change in count so it must have the same id as before.
3723 uint32_t id = last->rawPointerData.pointers[0].id;
3724 current->rawPointerData.pointers[0].id = id;
3725 current->rawPointerData.idToIndex[id] = 0;
3726 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3727 return;
3728 }
3729
3730 // General case.
3731 // We build a heap of squared euclidean distances between current and last pointers
3732 // associated with the current and last pointer indices. Then, we find the best
3733 // match (by distance) for each current pointer.
3734 // The pointers must have the same tool type but it is possible for them to
3735 // transition from hovering to touching or vice-versa while retaining the same id.
3736 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3737
3738 uint32_t heapSize = 0;
3739 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3740 currentPointerIndex++) {
3741 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3742 lastPointerIndex++) {
3743 const RawPointerData::Pointer& currentPointer =
3744 current->rawPointerData.pointers[currentPointerIndex];
3745 const RawPointerData::Pointer& lastPointer =
3746 last->rawPointerData.pointers[lastPointerIndex];
3747 if (currentPointer.toolType == lastPointer.toolType) {
3748 int64_t deltaX = currentPointer.x - lastPointer.x;
3749 int64_t deltaY = currentPointer.y - lastPointer.y;
3750
3751 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3752
3753 // Insert new element into the heap (sift up).
3754 heap[heapSize].currentPointerIndex = currentPointerIndex;
3755 heap[heapSize].lastPointerIndex = lastPointerIndex;
3756 heap[heapSize].distance = distance;
3757 heapSize += 1;
3758 }
3759 }
3760 }
3761
3762 // Heapify
3763 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3764 startIndex -= 1;
3765 for (uint32_t parentIndex = startIndex;;) {
3766 uint32_t childIndex = parentIndex * 2 + 1;
3767 if (childIndex >= heapSize) {
3768 break;
3769 }
3770
3771 if (childIndex + 1 < heapSize &&
3772 heap[childIndex + 1].distance < heap[childIndex].distance) {
3773 childIndex += 1;
3774 }
3775
3776 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3777 break;
3778 }
3779
3780 swap(heap[parentIndex], heap[childIndex]);
3781 parentIndex = childIndex;
3782 }
3783 }
3784
3785#if DEBUG_POINTER_ASSIGNMENT
3786 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3787 for (size_t i = 0; i < heapSize; i++) {
3788 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3789 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3790 }
3791#endif
3792
3793 // Pull matches out by increasing order of distance.
3794 // To avoid reassigning pointers that have already been matched, the loop keeps track
3795 // of which last and current pointers have been matched using the matchedXXXBits variables.
3796 // It also tracks the used pointer id bits.
3797 BitSet32 matchedLastBits(0);
3798 BitSet32 matchedCurrentBits(0);
3799 BitSet32 usedIdBits(0);
3800 bool first = true;
3801 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3802 while (heapSize > 0) {
3803 if (first) {
3804 // The first time through the loop, we just consume the root element of
3805 // the heap (the one with smallest distance).
3806 first = false;
3807 } else {
3808 // Previous iterations consumed the root element of the heap.
3809 // Pop root element off of the heap (sift down).
3810 heap[0] = heap[heapSize];
3811 for (uint32_t parentIndex = 0;;) {
3812 uint32_t childIndex = parentIndex * 2 + 1;
3813 if (childIndex >= heapSize) {
3814 break;
3815 }
3816
3817 if (childIndex + 1 < heapSize &&
3818 heap[childIndex + 1].distance < heap[childIndex].distance) {
3819 childIndex += 1;
3820 }
3821
3822 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3823 break;
3824 }
3825
3826 swap(heap[parentIndex], heap[childIndex]);
3827 parentIndex = childIndex;
3828 }
3829
3830#if DEBUG_POINTER_ASSIGNMENT
3831 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003832 for (size_t j = 0; j < heapSize; j++) {
3833 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3834 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003835 }
3836#endif
3837 }
3838
3839 heapSize -= 1;
3840
3841 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3842 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3843
3844 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3845 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3846
3847 matchedCurrentBits.markBit(currentPointerIndex);
3848 matchedLastBits.markBit(lastPointerIndex);
3849
3850 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3851 current->rawPointerData.pointers[currentPointerIndex].id = id;
3852 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3853 current->rawPointerData.markIdBit(id,
3854 current->rawPointerData.isHovering(
3855 currentPointerIndex));
3856 usedIdBits.markBit(id);
3857
3858#if DEBUG_POINTER_ASSIGNMENT
3859 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3860 ", distance=%" PRIu64,
3861 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3862#endif
3863 break;
3864 }
3865 }
3866
3867 // Assign fresh ids to pointers that were not matched in the process.
3868 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3869 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3870 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3871
3872 current->rawPointerData.pointers[currentPointerIndex].id = id;
3873 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3874 current->rawPointerData.markIdBit(id,
3875 current->rawPointerData.isHovering(currentPointerIndex));
3876
3877#if DEBUG_POINTER_ASSIGNMENT
3878 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3879#endif
3880 }
3881}
3882
3883int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3884 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3885 return AKEY_STATE_VIRTUAL;
3886 }
3887
3888 for (const VirtualKey& virtualKey : mVirtualKeys) {
3889 if (virtualKey.keyCode == keyCode) {
3890 return AKEY_STATE_UP;
3891 }
3892 }
3893
3894 return AKEY_STATE_UNKNOWN;
3895}
3896
3897int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3898 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3899 return AKEY_STATE_VIRTUAL;
3900 }
3901
3902 for (const VirtualKey& virtualKey : mVirtualKeys) {
3903 if (virtualKey.scanCode == scanCode) {
3904 return AKEY_STATE_UP;
3905 }
3906 }
3907
3908 return AKEY_STATE_UNKNOWN;
3909}
3910
3911bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3912 const int32_t* keyCodes, uint8_t* outFlags) {
3913 for (const VirtualKey& virtualKey : mVirtualKeys) {
3914 for (size_t i = 0; i < numCodes; i++) {
3915 if (virtualKey.keyCode == keyCodes[i]) {
3916 outFlags[i] = 1;
3917 }
3918 }
3919 }
3920
3921 return true;
3922}
3923
3924std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3925 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003926 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003927 return std::make_optional(mPointerController->getDisplayId());
3928 } else {
3929 return std::make_optional(mViewport.displayId);
3930 }
3931 }
3932 return std::nullopt;
3933}
3934
3935} // namespace android