blob: ea848355e0d79d3359ffac5fc36890af22a8b37a [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.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800400 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800401 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 }
403}
404
405void TouchInputMapper::resolveExternalStylusPresence() {
406 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800407 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700408 mExternalStylusConnected = !devices.empty();
409
410 if (!mExternalStylusConnected) {
411 resetExternalStylus();
412 }
413}
414
415void TouchInputMapper::configureParameters() {
416 // Use the pointer presentation mode for devices that do not support distinct
417 // multitouch. The spot-based presentation relies on being able to accurately
418 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100420 ? Parameters::GestureMode::SINGLE_TOUCH
421 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422
423 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800424 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
425 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100427 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100429 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700430 } else if (gestureModeString != "default") {
431 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
432 }
433 }
434
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800435 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100437 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800438 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800441 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
442 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 // The device is a cursor device with a touch pad attached.
444 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100445 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446 } else {
447 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100448 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449 }
450
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800451 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452
453 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
455 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100461 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100463 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700464 } else if (deviceTypeString != "default") {
465 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
466 }
467 }
468
Michael Wright227c5542020-07-02 18:30:52 +0100469 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800470 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
471 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472
473 mParameters.hasAssociatedDisplay = false;
474 mParameters.associatedDisplayIsExternal = false;
475 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100476 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
477 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700478 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100479 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800480 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800482 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
483 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
485 }
486 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800487 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488 mParameters.hasAssociatedDisplay = true;
489 }
490
491 // Initial downs on external touch devices should wake the device.
492 // Normally we don't do this for internal touch screens to prevent them from waking
493 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 mParameters.wake = getDeviceContext().isExternal();
495 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496}
497
498void TouchInputMapper::dumpParameters(std::string& dump) {
499 dump += INDENT3 "Parameters:\n";
500
Chris Yea03dd232020-09-08 19:21:09 -0700501 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502
Chris Yea03dd232020-09-08 19:21:09 -0700503 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700504
505 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
506 "displayId='%s'\n",
507 toString(mParameters.hasAssociatedDisplay),
508 toString(mParameters.associatedDisplayIsExternal),
509 mParameters.uniqueDisplayId.c_str());
510 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
511}
512
513void TouchInputMapper::configureRawPointerAxes() {
514 mRawPointerAxes.clear();
515}
516
517void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
518 dump += INDENT3 "Raw Touch Axes:\n";
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
531 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
532}
533
534bool TouchInputMapper::hasExternalStylus() const {
535 return mExternalStylusConnected;
536}
537
538/**
539 * Determine which DisplayViewport to use.
540 * 1. If display port is specified, return the matching viewport. If matching viewport not
541 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800542 * 2. Always use the suggested viewport from WindowManagerService for pointers.
543 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700544 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800545 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700546 */
547std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800548 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800549 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700550 if (displayPort) {
551 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800552 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700553 }
554
Michael Wright227c5542020-07-02 18:30:52 +0100555 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800556 std::optional<DisplayViewport> viewport =
557 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
558 if (viewport) {
559 return viewport;
560 } else {
561 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
562 mConfig.defaultPointerDisplayId);
563 }
564 }
565
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 // Check if uniqueDisplayId is specified in idc file.
567 if (!mParameters.uniqueDisplayId.empty()) {
568 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
569 }
570
571 ViewportType viewportTypeToUse;
572 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100573 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700574 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100575 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700576 }
577
578 std::optional<DisplayViewport> viewport =
579 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100580 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700581 ALOGW("Input device %s should be associated with external display, "
582 "fallback to internal one for the external viewport is not found.",
583 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100584 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700585 }
586
587 return viewport;
588 }
589
590 // No associated display, return a non-display viewport.
591 DisplayViewport newViewport;
592 // Raw width and height in the natural orientation.
593 int32_t rawWidth = mRawPointerAxes.getRawWidth();
594 int32_t rawHeight = mRawPointerAxes.getRawHeight();
595 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
596 return std::make_optional(newViewport);
597}
598
599void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100600 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700601
602 resolveExternalStylusPresence();
603
604 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100605 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800606 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700607 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100608 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700609 if (hasStylus()) {
610 mSource |= AINPUT_SOURCE_STYLUS;
611 }
Michael Wright227c5542020-07-02 18:30:52 +0100612 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700613 mParameters.hasAssociatedDisplay) {
614 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100615 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700616 if (hasStylus()) {
617 mSource |= AINPUT_SOURCE_STYLUS;
618 }
619 if (hasExternalStylus()) {
620 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
621 }
Michael Wright227c5542020-07-02 18:30:52 +0100622 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700623 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100624 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700625 } else {
626 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100627 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700628 }
629
630 // Ensure we have valid X and Y axes.
631 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
632 ALOGW("Touch device '%s' did not report support for X or Y axis! "
633 "The device will be inoperable.",
634 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100635 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700636 return;
637 }
638
639 // Get associated display dimensions.
640 std::optional<DisplayViewport> newViewport = findViewport();
641 if (!newViewport) {
642 ALOGI("Touch device '%s' could not query the properties of its associated "
643 "display. The device will be inoperable until the display size "
644 "becomes available.",
645 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100646 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700647 return;
648 }
649
650 // Raw width and height in the natural orientation.
651 int32_t rawWidth = mRawPointerAxes.getRawWidth();
652 int32_t rawHeight = mRawPointerAxes.getRawHeight();
653
654 bool viewportChanged = mViewport != *newViewport;
655 if (viewportChanged) {
656 mViewport = *newViewport;
657
Michael Wright227c5542020-07-02 18:30:52 +0100658 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700659 // Convert rotated viewport to natural surface coordinates.
660 int32_t naturalLogicalWidth, naturalLogicalHeight;
661 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
662 int32_t naturalPhysicalLeft, naturalPhysicalTop;
663 int32_t naturalDeviceWidth, naturalDeviceHeight;
664 switch (mViewport.orientation) {
665 case DISPLAY_ORIENTATION_90:
666 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
667 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
668 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
669 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800670 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700671 naturalPhysicalTop = mViewport.physicalLeft;
672 naturalDeviceWidth = mViewport.deviceHeight;
673 naturalDeviceHeight = mViewport.deviceWidth;
674 break;
675 case DISPLAY_ORIENTATION_180:
676 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
677 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
678 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
679 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
680 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
681 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
682 naturalDeviceWidth = mViewport.deviceWidth;
683 naturalDeviceHeight = mViewport.deviceHeight;
684 break;
685 case DISPLAY_ORIENTATION_270:
686 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
687 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
688 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
689 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
690 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800691 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700692 naturalDeviceWidth = mViewport.deviceHeight;
693 naturalDeviceHeight = mViewport.deviceWidth;
694 break;
695 case DISPLAY_ORIENTATION_0:
696 default:
697 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
698 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
699 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
700 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
701 naturalPhysicalLeft = mViewport.physicalLeft;
702 naturalPhysicalTop = mViewport.physicalTop;
703 naturalDeviceWidth = mViewport.deviceWidth;
704 naturalDeviceHeight = mViewport.deviceHeight;
705 break;
706 }
707
708 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
709 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
710 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
711 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
712 }
713
714 mPhysicalWidth = naturalPhysicalWidth;
715 mPhysicalHeight = naturalPhysicalHeight;
716 mPhysicalLeft = naturalPhysicalLeft;
717 mPhysicalTop = naturalPhysicalTop;
718
Arthur Hung4197f6b2020-03-16 15:39:59 +0800719 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
720 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700721 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
722 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800723 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
724 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700725
726 mSurfaceOrientation =
727 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
728 } else {
729 mPhysicalWidth = rawWidth;
730 mPhysicalHeight = rawHeight;
731 mPhysicalLeft = 0;
732 mPhysicalTop = 0;
733
Arthur Hung4197f6b2020-03-16 15:39:59 +0800734 mRawSurfaceWidth = rawWidth;
735 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700736 mSurfaceLeft = 0;
737 mSurfaceTop = 0;
738 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
739 }
740 }
741
742 // If moving between pointer modes, need to reset some state.
743 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
744 if (deviceModeChanged) {
745 mOrientedRanges.clear();
746 }
747
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800748 // Create pointer controller if needed.
Michael Wright227c5542020-07-02 18:30:52 +0100749 if (mDeviceMode == DeviceMode::POINTER ||
750 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800751 if (mPointerController == nullptr) {
752 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700753 }
754 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100755 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700756 }
757
758 if (viewportChanged || deviceModeChanged) {
759 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
760 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800761 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700762 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
763
764 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800765 mXScale = float(mRawSurfaceWidth) / rawWidth;
766 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700767 mXTranslate = -mSurfaceLeft;
768 mYTranslate = -mSurfaceTop;
769 mXPrecision = 1.0f / mXScale;
770 mYPrecision = 1.0f / mYScale;
771
772 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
773 mOrientedRanges.x.source = mSource;
774 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
775 mOrientedRanges.y.source = mSource;
776
777 configureVirtualKeys();
778
779 // Scale factor for terms that are not oriented in a particular axis.
780 // If the pixels are square then xScale == yScale otherwise we fake it
781 // by choosing an average.
782 mGeometricScale = avg(mXScale, mYScale);
783
784 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800785 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700786
787 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100788 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700789 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
790 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
791 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
792 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
793 } else {
794 mSizeScale = 0.0f;
795 }
796
797 mOrientedRanges.haveTouchSize = true;
798 mOrientedRanges.haveToolSize = true;
799 mOrientedRanges.haveSize = true;
800
801 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
802 mOrientedRanges.touchMajor.source = mSource;
803 mOrientedRanges.touchMajor.min = 0;
804 mOrientedRanges.touchMajor.max = diagonalSize;
805 mOrientedRanges.touchMajor.flat = 0;
806 mOrientedRanges.touchMajor.fuzz = 0;
807 mOrientedRanges.touchMajor.resolution = 0;
808
809 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
810 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
811
812 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
813 mOrientedRanges.toolMajor.source = mSource;
814 mOrientedRanges.toolMajor.min = 0;
815 mOrientedRanges.toolMajor.max = diagonalSize;
816 mOrientedRanges.toolMajor.flat = 0;
817 mOrientedRanges.toolMajor.fuzz = 0;
818 mOrientedRanges.toolMajor.resolution = 0;
819
820 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
821 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
822
823 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
824 mOrientedRanges.size.source = mSource;
825 mOrientedRanges.size.min = 0;
826 mOrientedRanges.size.max = 1.0;
827 mOrientedRanges.size.flat = 0;
828 mOrientedRanges.size.fuzz = 0;
829 mOrientedRanges.size.resolution = 0;
830 } else {
831 mSizeScale = 0.0f;
832 }
833
834 // Pressure factors.
835 mPressureScale = 0;
836 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100837 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
838 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700839 if (mCalibration.havePressureScale) {
840 mPressureScale = mCalibration.pressureScale;
841 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
842 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
843 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
844 }
845 }
846
847 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
848 mOrientedRanges.pressure.source = mSource;
849 mOrientedRanges.pressure.min = 0;
850 mOrientedRanges.pressure.max = pressureMax;
851 mOrientedRanges.pressure.flat = 0;
852 mOrientedRanges.pressure.fuzz = 0;
853 mOrientedRanges.pressure.resolution = 0;
854
855 // Tilt
856 mTiltXCenter = 0;
857 mTiltXScale = 0;
858 mTiltYCenter = 0;
859 mTiltYScale = 0;
860 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
861 if (mHaveTilt) {
862 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
863 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
864 mTiltXScale = M_PI / 180;
865 mTiltYScale = M_PI / 180;
866
867 mOrientedRanges.haveTilt = true;
868
869 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
870 mOrientedRanges.tilt.source = mSource;
871 mOrientedRanges.tilt.min = 0;
872 mOrientedRanges.tilt.max = M_PI_2;
873 mOrientedRanges.tilt.flat = 0;
874 mOrientedRanges.tilt.fuzz = 0;
875 mOrientedRanges.tilt.resolution = 0;
876 }
877
878 // Orientation
879 mOrientationScale = 0;
880 if (mHaveTilt) {
881 mOrientedRanges.haveOrientation = true;
882
883 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
884 mOrientedRanges.orientation.source = mSource;
885 mOrientedRanges.orientation.min = -M_PI;
886 mOrientedRanges.orientation.max = M_PI;
887 mOrientedRanges.orientation.flat = 0;
888 mOrientedRanges.orientation.fuzz = 0;
889 mOrientedRanges.orientation.resolution = 0;
890 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100891 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700892 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100893 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700894 if (mRawPointerAxes.orientation.valid) {
895 if (mRawPointerAxes.orientation.maxValue > 0) {
896 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
897 } else if (mRawPointerAxes.orientation.minValue < 0) {
898 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
899 } else {
900 mOrientationScale = 0;
901 }
902 }
903 }
904
905 mOrientedRanges.haveOrientation = true;
906
907 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
908 mOrientedRanges.orientation.source = mSource;
909 mOrientedRanges.orientation.min = -M_PI_2;
910 mOrientedRanges.orientation.max = M_PI_2;
911 mOrientedRanges.orientation.flat = 0;
912 mOrientedRanges.orientation.fuzz = 0;
913 mOrientedRanges.orientation.resolution = 0;
914 }
915
916 // Distance
917 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100918 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
919 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700920 if (mCalibration.haveDistanceScale) {
921 mDistanceScale = mCalibration.distanceScale;
922 } else {
923 mDistanceScale = 1.0f;
924 }
925 }
926
927 mOrientedRanges.haveDistance = true;
928
929 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
930 mOrientedRanges.distance.source = mSource;
931 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
932 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
933 mOrientedRanges.distance.flat = 0;
934 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
935 mOrientedRanges.distance.resolution = 0;
936 }
937
938 // Compute oriented precision, scales and ranges.
939 // Note that the maximum value reported is an inclusive maximum value so it is one
940 // unit less than the total width or height of surface.
941 switch (mSurfaceOrientation) {
942 case DISPLAY_ORIENTATION_90:
943 case DISPLAY_ORIENTATION_270:
944 mOrientedXPrecision = mYPrecision;
945 mOrientedYPrecision = mXPrecision;
946
947 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800948 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700949 mOrientedRanges.x.flat = 0;
950 mOrientedRanges.x.fuzz = 0;
951 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
952
953 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800954 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700955 mOrientedRanges.y.flat = 0;
956 mOrientedRanges.y.fuzz = 0;
957 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
958 break;
959
960 default:
961 mOrientedXPrecision = mXPrecision;
962 mOrientedYPrecision = mYPrecision;
963
964 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800965 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966 mOrientedRanges.x.flat = 0;
967 mOrientedRanges.x.fuzz = 0;
968 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
969
970 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800971 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700972 mOrientedRanges.y.flat = 0;
973 mOrientedRanges.y.fuzz = 0;
974 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
975 break;
976 }
977
978 // Location
979 updateAffineTransformation();
980
Michael Wright227c5542020-07-02 18:30:52 +0100981 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700982 // Compute pointer gesture detection parameters.
983 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +0800984 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700985
986 // Scale movements such that one whole swipe of the touch pad covers a
987 // given area relative to the diagonal size of the display when no acceleration
988 // is applied.
989 // Assume that the touch pad has a square aspect ratio such that movements in
990 // X and Y of the same number of raw units cover the same physical distance.
991 mPointerXMovementScale =
992 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
993 mPointerYMovementScale = mPointerXMovementScale;
994
995 // Scale zooms to cover a smaller range of the display than movements do.
996 // This value determines the area around the pointer that is affected by freeform
997 // pointer gestures.
998 mPointerXZoomScale =
999 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1000 mPointerYZoomScale = mPointerXZoomScale;
1001
1002 // Max width between pointers to detect a swipe gesture is more than some fraction
1003 // of the diagonal axis of the touch pad. Touches that are wider than this are
1004 // translated into freeform gestures.
1005 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1006
1007 // Abort current pointer usages because the state has changed.
1008 abortPointerUsage(when, 0 /*policyFlags*/);
1009 }
1010
1011 // Inform the dispatcher about the changes.
1012 *outResetNeeded = true;
1013 bumpGeneration();
1014 }
1015}
1016
1017void TouchInputMapper::dumpSurface(std::string& dump) {
1018 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001019 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1020 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001021 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1022 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001023 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1024 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001025 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1026 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1027 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1028 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1029 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1030}
1031
1032void TouchInputMapper::configureVirtualKeys() {
1033 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001034 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035
1036 mVirtualKeys.clear();
1037
1038 if (virtualKeyDefinitions.size() == 0) {
1039 return;
1040 }
1041
1042 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1043 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1044 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1045 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1046
1047 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1048 VirtualKey virtualKey;
1049
1050 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1051 int32_t keyCode;
1052 int32_t dummyKeyMetaState;
1053 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001054 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1055 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001056 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1057 continue; // drop the key
1058 }
1059
1060 virtualKey.keyCode = keyCode;
1061 virtualKey.flags = flags;
1062
1063 // convert the key definition's display coordinates into touch coordinates for a hit box
1064 int32_t halfWidth = virtualKeyDefinition.width / 2;
1065 int32_t halfHeight = virtualKeyDefinition.height / 2;
1066
1067 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001068 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001069 touchScreenLeft;
1070 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001071 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001072 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001073 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1074 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001075 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001076 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1077 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001078 touchScreenTop;
1079 mVirtualKeys.push_back(virtualKey);
1080 }
1081}
1082
1083void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1084 if (!mVirtualKeys.empty()) {
1085 dump += INDENT3 "Virtual Keys:\n";
1086
1087 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1088 const VirtualKey& virtualKey = mVirtualKeys[i];
1089 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1090 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1091 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1092 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1093 }
1094 }
1095}
1096
1097void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001098 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001099 Calibration& out = mCalibration;
1100
1101 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001102 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001103 String8 sizeCalibrationString;
1104 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1105 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001106 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001107 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001108 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001110 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001112 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001114 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001115 } else if (sizeCalibrationString != "default") {
1116 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1117 }
1118 }
1119
1120 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1121 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1122 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1123
1124 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001125 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 String8 pressureCalibrationString;
1127 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1128 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001129 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001130 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001131 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001133 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001134 } else if (pressureCalibrationString != "default") {
1135 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1136 pressureCalibrationString.string());
1137 }
1138 }
1139
1140 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1141
1142 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 String8 orientationCalibrationString;
1145 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1146 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001147 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001149 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001151 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001152 } else if (orientationCalibrationString != "default") {
1153 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1154 orientationCalibrationString.string());
1155 }
1156 }
1157
1158 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001159 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 String8 distanceCalibrationString;
1161 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1162 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001164 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001165 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 } else if (distanceCalibrationString != "default") {
1167 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1168 distanceCalibrationString.string());
1169 }
1170 }
1171
1172 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1173
Michael Wright227c5542020-07-02 18:30:52 +01001174 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 String8 coverageCalibrationString;
1176 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1177 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001178 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001180 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 } else if (coverageCalibrationString != "default") {
1182 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1183 coverageCalibrationString.string());
1184 }
1185 }
1186}
1187
1188void TouchInputMapper::resolveCalibration() {
1189 // Size
1190 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001191 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1192 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 }
1194 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001195 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 }
1197
1198 // Pressure
1199 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001200 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1201 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 }
1203 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001204 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 }
1206
1207 // Orientation
1208 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001209 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1210 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 }
1212 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001213 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 }
1215
1216 // Distance
1217 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001218 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1219 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 }
1221 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001222 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 }
1224
1225 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001226 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1227 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229}
1230
1231void TouchInputMapper::dumpCalibration(std::string& dump) {
1232 dump += INDENT3 "Calibration:\n";
1233
1234 // Size
1235 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001236 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 dump += INDENT4 "touch.size.calibration: none\n";
1238 break;
Michael Wright227c5542020-07-02 18:30:52 +01001239 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 dump += INDENT4 "touch.size.calibration: geometric\n";
1241 break;
Michael Wright227c5542020-07-02 18:30:52 +01001242 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 dump += INDENT4 "touch.size.calibration: diameter\n";
1244 break;
Michael Wright227c5542020-07-02 18:30:52 +01001245 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 dump += INDENT4 "touch.size.calibration: box\n";
1247 break;
Michael Wright227c5542020-07-02 18:30:52 +01001248 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 dump += INDENT4 "touch.size.calibration: area\n";
1250 break;
1251 default:
1252 ALOG_ASSERT(false);
1253 }
1254
1255 if (mCalibration.haveSizeScale) {
1256 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1257 }
1258
1259 if (mCalibration.haveSizeBias) {
1260 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1261 }
1262
1263 if (mCalibration.haveSizeIsSummed) {
1264 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1265 toString(mCalibration.sizeIsSummed));
1266 }
1267
1268 // Pressure
1269 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001270 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 dump += INDENT4 "touch.pressure.calibration: none\n";
1272 break;
Michael Wright227c5542020-07-02 18:30:52 +01001273 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274 dump += INDENT4 "touch.pressure.calibration: physical\n";
1275 break;
Michael Wright227c5542020-07-02 18:30:52 +01001276 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1278 break;
1279 default:
1280 ALOG_ASSERT(false);
1281 }
1282
1283 if (mCalibration.havePressureScale) {
1284 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1285 }
1286
1287 // Orientation
1288 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001289 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 dump += INDENT4 "touch.orientation.calibration: none\n";
1291 break;
Michael Wright227c5542020-07-02 18:30:52 +01001292 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1294 break;
Michael Wright227c5542020-07-02 18:30:52 +01001295 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 dump += INDENT4 "touch.orientation.calibration: vector\n";
1297 break;
1298 default:
1299 ALOG_ASSERT(false);
1300 }
1301
1302 // Distance
1303 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001304 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 dump += INDENT4 "touch.distance.calibration: none\n";
1306 break;
Michael Wright227c5542020-07-02 18:30:52 +01001307 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 dump += INDENT4 "touch.distance.calibration: scaled\n";
1309 break;
1310 default:
1311 ALOG_ASSERT(false);
1312 }
1313
1314 if (mCalibration.haveDistanceScale) {
1315 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1316 }
1317
1318 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001319 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 dump += INDENT4 "touch.coverage.calibration: none\n";
1321 break;
Michael Wright227c5542020-07-02 18:30:52 +01001322 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001323 dump += INDENT4 "touch.coverage.calibration: box\n";
1324 break;
1325 default:
1326 ALOG_ASSERT(false);
1327 }
1328}
1329
1330void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1331 dump += INDENT3 "Affine Transformation:\n";
1332
1333 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1334 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1335 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1336 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1337 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1338 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1339}
1340
1341void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001342 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 mSurfaceOrientation);
1344}
1345
1346void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001347 mCursorButtonAccumulator.reset(getDeviceContext());
1348 mCursorScrollAccumulator.reset(getDeviceContext());
1349 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350
1351 mPointerVelocityControl.reset();
1352 mWheelXVelocityControl.reset();
1353 mWheelYVelocityControl.reset();
1354
1355 mRawStatesPending.clear();
1356 mCurrentRawState.clear();
1357 mCurrentCookedState.clear();
1358 mLastRawState.clear();
1359 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001360 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361 mSentHoverEnter = false;
1362 mHavePointerIds = false;
1363 mCurrentMotionAborted = false;
1364 mDownTime = 0;
1365
1366 mCurrentVirtualKey.down = false;
1367
1368 mPointerGesture.reset();
1369 mPointerSimple.reset();
1370 resetExternalStylus();
1371
1372 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001373 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374 mPointerController->clearSpots();
1375 }
1376
1377 InputMapper::reset(when);
1378}
1379
1380void TouchInputMapper::resetExternalStylus() {
1381 mExternalStylusState.clear();
1382 mExternalStylusId = -1;
1383 mExternalStylusFusionTimeout = LLONG_MAX;
1384 mExternalStylusDataPending = false;
1385}
1386
1387void TouchInputMapper::clearStylusDataPendingFlags() {
1388 mExternalStylusDataPending = false;
1389 mExternalStylusFusionTimeout = LLONG_MAX;
1390}
1391
1392void TouchInputMapper::process(const RawEvent* rawEvent) {
1393 mCursorButtonAccumulator.process(rawEvent);
1394 mCursorScrollAccumulator.process(rawEvent);
1395 mTouchButtonAccumulator.process(rawEvent);
1396
1397 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1398 sync(rawEvent->when);
1399 }
1400}
1401
1402void TouchInputMapper::sync(nsecs_t when) {
1403 const RawState* last =
1404 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1405
1406 // Push a new state.
1407 mRawStatesPending.emplace_back();
1408
1409 RawState* next = &mRawStatesPending.back();
1410 next->clear();
1411 next->when = when;
1412
1413 // Sync button state.
1414 next->buttonState =
1415 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1416
1417 // Sync scroll
1418 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1419 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1420 mCursorScrollAccumulator.finishSync();
1421
1422 // Sync touch
1423 syncTouch(when, next);
1424
1425 // Assign pointer ids.
1426 if (!mHavePointerIds) {
1427 assignPointerIds(last, next);
1428 }
1429
1430#if DEBUG_RAW_EVENTS
1431 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001432 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001433 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1434 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001435 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1436 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001437#endif
1438
1439 processRawTouches(false /*timeout*/);
1440}
1441
1442void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001443 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 // Drop all input if the device is disabled.
1445 mCurrentRawState.clear();
1446 mRawStatesPending.clear();
1447 return;
1448 }
1449
1450 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1451 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1452 // touching the current state will only observe the events that have been dispatched to the
1453 // rest of the pipeline.
1454 const size_t N = mRawStatesPending.size();
1455 size_t count;
1456 for (count = 0; count < N; count++) {
1457 const RawState& next = mRawStatesPending[count];
1458
1459 // A failure to assign the stylus id means that we're waiting on stylus data
1460 // and so should defer the rest of the pipeline.
1461 if (assignExternalStylusId(next, timeout)) {
1462 break;
1463 }
1464
1465 // All ready to go.
1466 clearStylusDataPendingFlags();
1467 mCurrentRawState.copyFrom(next);
1468 if (mCurrentRawState.when < mLastRawState.when) {
1469 mCurrentRawState.when = mLastRawState.when;
1470 }
1471 cookAndDispatch(mCurrentRawState.when);
1472 }
1473 if (count != 0) {
1474 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1475 }
1476
1477 if (mExternalStylusDataPending) {
1478 if (timeout) {
1479 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1480 clearStylusDataPendingFlags();
1481 mCurrentRawState.copyFrom(mLastRawState);
1482#if DEBUG_STYLUS_FUSION
1483 ALOGD("Timeout expired, synthesizing event with new stylus data");
1484#endif
1485 cookAndDispatch(when);
1486 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1487 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1488 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1489 }
1490 }
1491}
1492
1493void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1494 // Always start with a clean state.
1495 mCurrentCookedState.clear();
1496
1497 // Apply stylus buttons to current raw state.
1498 applyExternalStylusButtonState(when);
1499
1500 // Handle policy on initial down or hover events.
1501 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1502 mCurrentRawState.rawPointerData.pointerCount != 0;
1503
1504 uint32_t policyFlags = 0;
1505 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1506 if (initialDown || buttonsPressed) {
1507 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001508 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001509 getContext()->fadePointer();
1510 }
1511
1512 if (mParameters.wake) {
1513 policyFlags |= POLICY_FLAG_WAKE;
1514 }
1515 }
1516
1517 // Consume raw off-screen touches before cooking pointer data.
1518 // If touches are consumed, subsequent code will not receive any pointer data.
1519 if (consumeRawTouches(when, policyFlags)) {
1520 mCurrentRawState.rawPointerData.clear();
1521 }
1522
1523 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1524 // with cooked pointer data that has the same ids and indices as the raw data.
1525 // The following code can use either the raw or cooked data, as needed.
1526 cookPointerData();
1527
1528 // Apply stylus pressure to current cooked state.
1529 applyExternalStylusTouchState(when);
1530
1531 // Synthesize key down from raw buttons if needed.
1532 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1533 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1534 mCurrentCookedState.buttonState);
1535
1536 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001537 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001538 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1539 uint32_t id = idBits.clearFirstMarkedBit();
1540 const RawPointerData::Pointer& pointer =
1541 mCurrentRawState.rawPointerData.pointerForId(id);
1542 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1543 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1544 mCurrentCookedState.stylusIdBits.markBit(id);
1545 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1546 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1547 mCurrentCookedState.fingerIdBits.markBit(id);
1548 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1549 mCurrentCookedState.mouseIdBits.markBit(id);
1550 }
1551 }
1552 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1553 uint32_t id = idBits.clearFirstMarkedBit();
1554 const RawPointerData::Pointer& pointer =
1555 mCurrentRawState.rawPointerData.pointerForId(id);
1556 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1557 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1558 mCurrentCookedState.stylusIdBits.markBit(id);
1559 }
1560 }
1561
1562 // Stylus takes precedence over all tools, then mouse, then finger.
1563 PointerUsage pointerUsage = mPointerUsage;
1564 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1565 mCurrentCookedState.mouseIdBits.clear();
1566 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001567 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001568 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1569 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001570 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001571 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1572 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001573 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001574 }
1575
1576 dispatchPointerUsage(when, policyFlags, pointerUsage);
1577 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001578 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001580 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1581 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001582
1583 mPointerController->setButtonState(mCurrentRawState.buttonState);
1584 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1585 mCurrentCookedState.cookedPointerData.idToIndex,
1586 mCurrentCookedState.cookedPointerData.touchingIdBits,
1587 mViewport.displayId);
1588 }
1589
1590 if (!mCurrentMotionAborted) {
1591 dispatchButtonRelease(when, policyFlags);
1592 dispatchHoverExit(when, policyFlags);
1593 dispatchTouches(when, policyFlags);
1594 dispatchHoverEnterAndMove(when, policyFlags);
1595 dispatchButtonPress(when, policyFlags);
1596 }
1597
1598 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1599 mCurrentMotionAborted = false;
1600 }
1601 }
1602
1603 // Synthesize key up from raw buttons if needed.
1604 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1605 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1606 mCurrentCookedState.buttonState);
1607
1608 // Clear some transient state.
1609 mCurrentRawState.rawVScroll = 0;
1610 mCurrentRawState.rawHScroll = 0;
1611
1612 // Copy current touch to last touch in preparation for the next cycle.
1613 mLastRawState.copyFrom(mCurrentRawState);
1614 mLastCookedState.copyFrom(mCurrentCookedState);
1615}
1616
1617void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001618 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001619 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1620 }
1621}
1622
1623void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1624 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1625 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1626
1627 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1628 float pressure = mExternalStylusState.pressure;
1629 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1630 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1631 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1632 }
1633 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1634 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1635
1636 PointerProperties& properties =
1637 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1638 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1639 properties.toolType = mExternalStylusState.toolType;
1640 }
1641 }
1642}
1643
1644bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001645 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001646 return false;
1647 }
1648
1649 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1650 state.rawPointerData.pointerCount != 0;
1651 if (initialDown) {
1652 if (mExternalStylusState.pressure != 0.0f) {
1653#if DEBUG_STYLUS_FUSION
1654 ALOGD("Have both stylus and touch data, beginning fusion");
1655#endif
1656 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1657 } else if (timeout) {
1658#if DEBUG_STYLUS_FUSION
1659 ALOGD("Timeout expired, assuming touch is not a stylus.");
1660#endif
1661 resetExternalStylus();
1662 } else {
1663 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1664 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1665 }
1666#if DEBUG_STYLUS_FUSION
1667 ALOGD("No stylus data but stylus is connected, requesting timeout "
1668 "(%" PRId64 "ms)",
1669 mExternalStylusFusionTimeout);
1670#endif
1671 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1672 return true;
1673 }
1674 }
1675
1676 // Check if the stylus pointer has gone up.
1677 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1678#if DEBUG_STYLUS_FUSION
1679 ALOGD("Stylus pointer is going up");
1680#endif
1681 mExternalStylusId = -1;
1682 }
1683
1684 return false;
1685}
1686
1687void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001688 if (mDeviceMode == DeviceMode::POINTER) {
1689 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001690 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1691 }
Michael Wright227c5542020-07-02 18:30:52 +01001692 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001693 if (mExternalStylusFusionTimeout < when) {
1694 processRawTouches(true /*timeout*/);
1695 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1696 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1697 }
1698 }
1699}
1700
1701void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1702 mExternalStylusState.copyFrom(state);
1703 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1704 // We're either in the middle of a fused stream of data or we're waiting on data before
1705 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1706 // data.
1707 mExternalStylusDataPending = true;
1708 processRawTouches(false /*timeout*/);
1709 }
1710}
1711
1712bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1713 // Check for release of a virtual key.
1714 if (mCurrentVirtualKey.down) {
1715 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1716 // Pointer went up while virtual key was down.
1717 mCurrentVirtualKey.down = false;
1718 if (!mCurrentVirtualKey.ignored) {
1719#if DEBUG_VIRTUAL_KEYS
1720 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1721 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1722#endif
1723 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1724 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1725 }
1726 return true;
1727 }
1728
1729 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1730 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1731 const RawPointerData::Pointer& pointer =
1732 mCurrentRawState.rawPointerData.pointerForId(id);
1733 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1734 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1735 // Pointer is still within the space of the virtual key.
1736 return true;
1737 }
1738 }
1739
1740 // Pointer left virtual key area or another pointer also went down.
1741 // Send key cancellation but do not consume the touch yet.
1742 // This is useful when the user swipes through from the virtual key area
1743 // into the main display surface.
1744 mCurrentVirtualKey.down = false;
1745 if (!mCurrentVirtualKey.ignored) {
1746#if DEBUG_VIRTUAL_KEYS
1747 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1748 mCurrentVirtualKey.scanCode);
1749#endif
1750 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1751 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1752 AKEY_EVENT_FLAG_CANCELED);
1753 }
1754 }
1755
1756 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1757 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1758 // Pointer just went down. Check for virtual key press or off-screen touches.
1759 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1760 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001761 // Exclude unscaled device for inside surface checking.
1762 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001763 // If exactly one pointer went down, check for virtual key hit.
1764 // Otherwise we will drop the entire stroke.
1765 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1766 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1767 if (virtualKey) {
1768 mCurrentVirtualKey.down = true;
1769 mCurrentVirtualKey.downTime = when;
1770 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1771 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1772 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001773 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1774 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001775
1776 if (!mCurrentVirtualKey.ignored) {
1777#if DEBUG_VIRTUAL_KEYS
1778 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1779 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1780#endif
1781 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1782 AKEY_EVENT_FLAG_FROM_SYSTEM |
1783 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1784 }
1785 }
1786 }
1787 return true;
1788 }
1789 }
1790
1791 // Disable all virtual key touches that happen within a short time interval of the
1792 // most recent touch within the screen area. The idea is to filter out stray
1793 // virtual key presses when interacting with the touch screen.
1794 //
1795 // Problems we're trying to solve:
1796 //
1797 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1798 // virtual key area that is implemented by a separate touch panel and accidentally
1799 // triggers a virtual key.
1800 //
1801 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1802 // area and accidentally triggers a virtual key. This often happens when virtual keys
1803 // are layed out below the screen near to where the on screen keyboard's space bar
1804 // is displayed.
1805 if (mConfig.virtualKeyQuietTime > 0 &&
1806 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001807 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001808 }
1809 return false;
1810}
1811
1812void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1813 int32_t keyEventAction, int32_t keyEventFlags) {
1814 int32_t keyCode = mCurrentVirtualKey.keyCode;
1815 int32_t scanCode = mCurrentVirtualKey.scanCode;
1816 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001817 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001818 policyFlags |= POLICY_FLAG_VIRTUAL;
1819
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001820 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1821 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1822 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001823 getListener()->notifyKey(&args);
1824}
1825
1826void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1827 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1828 if (!currentIdBits.isEmpty()) {
1829 int32_t metaState = getContext()->getGlobalMetaState();
1830 int32_t buttonState = mCurrentCookedState.buttonState;
1831 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1832 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1833 mCurrentCookedState.cookedPointerData.pointerProperties,
1834 mCurrentCookedState.cookedPointerData.pointerCoords,
1835 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1836 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1837 mCurrentMotionAborted = true;
1838 }
1839}
1840
1841void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1842 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1843 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1844 int32_t metaState = getContext()->getGlobalMetaState();
1845 int32_t buttonState = mCurrentCookedState.buttonState;
1846
1847 if (currentIdBits == lastIdBits) {
1848 if (!currentIdBits.isEmpty()) {
1849 // No pointer id changes so this is a move event.
1850 // The listener takes care of batching moves so we don't have to deal with that here.
1851 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1852 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1853 mCurrentCookedState.cookedPointerData.pointerProperties,
1854 mCurrentCookedState.cookedPointerData.pointerCoords,
1855 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1856 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1857 }
1858 } else {
1859 // There may be pointers going up and pointers going down and pointers moving
1860 // all at the same time.
1861 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1862 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1863 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1864 BitSet32 dispatchedIdBits(lastIdBits.value);
1865
1866 // Update last coordinates of pointers that have moved so that we observe the new
1867 // pointer positions at the same time as other pointers that have just gone up.
1868 bool moveNeeded =
1869 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1870 mCurrentCookedState.cookedPointerData.pointerCoords,
1871 mCurrentCookedState.cookedPointerData.idToIndex,
1872 mLastCookedState.cookedPointerData.pointerProperties,
1873 mLastCookedState.cookedPointerData.pointerCoords,
1874 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1875 if (buttonState != mLastCookedState.buttonState) {
1876 moveNeeded = true;
1877 }
1878
1879 // Dispatch pointer up events.
1880 while (!upIdBits.isEmpty()) {
1881 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001882 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1883 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1884 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001885 mLastCookedState.cookedPointerData.pointerProperties,
1886 mLastCookedState.cookedPointerData.pointerCoords,
1887 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1888 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1889 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001890 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001891 }
1892
1893 // Dispatch move events if any of the remaining pointers moved from their old locations.
1894 // Although applications receive new locations as part of individual pointer up
1895 // events, they do not generally handle them except when presented in a move event.
1896 if (moveNeeded && !moveIdBits.isEmpty()) {
1897 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1898 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1899 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1900 mCurrentCookedState.cookedPointerData.pointerCoords,
1901 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1902 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1903 }
1904
1905 // Dispatch pointer down events using the new pointer locations.
1906 while (!downIdBits.isEmpty()) {
1907 uint32_t downId = downIdBits.clearFirstMarkedBit();
1908 dispatchedIdBits.markBit(downId);
1909
1910 if (dispatchedIdBits.count() == 1) {
1911 // First pointer is going down. Set down time.
1912 mDownTime = when;
1913 }
1914
1915 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1916 metaState, buttonState, 0,
1917 mCurrentCookedState.cookedPointerData.pointerProperties,
1918 mCurrentCookedState.cookedPointerData.pointerCoords,
1919 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1920 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1921 }
1922 }
1923}
1924
1925void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1926 if (mSentHoverEnter &&
1927 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1928 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1929 int32_t metaState = getContext()->getGlobalMetaState();
1930 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1931 mLastCookedState.buttonState, 0,
1932 mLastCookedState.cookedPointerData.pointerProperties,
1933 mLastCookedState.cookedPointerData.pointerCoords,
1934 mLastCookedState.cookedPointerData.idToIndex,
1935 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1936 mOrientedYPrecision, mDownTime);
1937 mSentHoverEnter = false;
1938 }
1939}
1940
1941void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1942 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1943 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1944 int32_t metaState = getContext()->getGlobalMetaState();
1945 if (!mSentHoverEnter) {
1946 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1947 metaState, mCurrentRawState.buttonState, 0,
1948 mCurrentCookedState.cookedPointerData.pointerProperties,
1949 mCurrentCookedState.cookedPointerData.pointerCoords,
1950 mCurrentCookedState.cookedPointerData.idToIndex,
1951 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1952 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1953 mSentHoverEnter = true;
1954 }
1955
1956 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1957 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 }
1964}
1965
1966void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1967 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1968 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1969 const int32_t metaState = getContext()->getGlobalMetaState();
1970 int32_t buttonState = mLastCookedState.buttonState;
1971 while (!releasedButtons.isEmpty()) {
1972 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
1973 buttonState &= ~actionButton;
1974 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1975 actionButton, 0, metaState, buttonState, 0,
1976 mCurrentCookedState.cookedPointerData.pointerProperties,
1977 mCurrentCookedState.cookedPointerData.pointerCoords,
1978 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
1979 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1980 }
1981}
1982
1983void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
1984 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
1985 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
1986 const int32_t metaState = getContext()->getGlobalMetaState();
1987 int32_t buttonState = mLastCookedState.buttonState;
1988 while (!pressedButtons.isEmpty()) {
1989 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
1990 buttonState |= actionButton;
1991 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
1992 0, metaState, buttonState, 0,
1993 mCurrentCookedState.cookedPointerData.pointerProperties,
1994 mCurrentCookedState.cookedPointerData.pointerCoords,
1995 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
1996 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1997 }
1998}
1999
2000const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2001 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2002 return cookedPointerData.touchingIdBits;
2003 }
2004 return cookedPointerData.hoveringIdBits;
2005}
2006
2007void TouchInputMapper::cookPointerData() {
2008 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2009
2010 mCurrentCookedState.cookedPointerData.clear();
2011 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2012 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2013 mCurrentRawState.rawPointerData.hoveringIdBits;
2014 mCurrentCookedState.cookedPointerData.touchingIdBits =
2015 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002016 mCurrentCookedState.cookedPointerData.canceledIdBits =
2017 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002018
2019 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2020 mCurrentCookedState.buttonState = 0;
2021 } else {
2022 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2023 }
2024
2025 // Walk through the the active pointers and map device coordinates onto
2026 // surface coordinates and adjust for display orientation.
2027 for (uint32_t i = 0; i < currentPointerCount; i++) {
2028 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2029
2030 // Size
2031 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2032 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002033 case Calibration::SizeCalibration::GEOMETRIC:
2034 case Calibration::SizeCalibration::DIAMETER:
2035 case Calibration::SizeCalibration::BOX:
2036 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002037 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2038 touchMajor = in.touchMajor;
2039 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2040 toolMajor = in.toolMajor;
2041 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2042 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2043 : in.touchMajor;
2044 } else if (mRawPointerAxes.touchMajor.valid) {
2045 toolMajor = touchMajor = in.touchMajor;
2046 toolMinor = touchMinor =
2047 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2048 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2049 : in.touchMajor;
2050 } else if (mRawPointerAxes.toolMajor.valid) {
2051 touchMajor = toolMajor = in.toolMajor;
2052 touchMinor = toolMinor =
2053 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2054 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2055 : in.toolMajor;
2056 } else {
2057 ALOG_ASSERT(false,
2058 "No touch or tool axes. "
2059 "Size calibration should have been resolved to NONE.");
2060 touchMajor = 0;
2061 touchMinor = 0;
2062 toolMajor = 0;
2063 toolMinor = 0;
2064 size = 0;
2065 }
2066
2067 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2068 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2069 if (touchingCount > 1) {
2070 touchMajor /= touchingCount;
2071 touchMinor /= touchingCount;
2072 toolMajor /= touchingCount;
2073 toolMinor /= touchingCount;
2074 size /= touchingCount;
2075 }
2076 }
2077
Michael Wright227c5542020-07-02 18:30:52 +01002078 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002079 touchMajor *= mGeometricScale;
2080 touchMinor *= mGeometricScale;
2081 toolMajor *= mGeometricScale;
2082 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002083 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002084 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2085 touchMinor = touchMajor;
2086 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2087 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002088 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089 touchMinor = touchMajor;
2090 toolMinor = toolMajor;
2091 }
2092
2093 mCalibration.applySizeScaleAndBias(&touchMajor);
2094 mCalibration.applySizeScaleAndBias(&touchMinor);
2095 mCalibration.applySizeScaleAndBias(&toolMajor);
2096 mCalibration.applySizeScaleAndBias(&toolMinor);
2097 size *= mSizeScale;
2098 break;
2099 default:
2100 touchMajor = 0;
2101 touchMinor = 0;
2102 toolMajor = 0;
2103 toolMinor = 0;
2104 size = 0;
2105 break;
2106 }
2107
2108 // Pressure
2109 float pressure;
2110 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002111 case Calibration::PressureCalibration::PHYSICAL:
2112 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113 pressure = in.pressure * mPressureScale;
2114 break;
2115 default:
2116 pressure = in.isHovering ? 0 : 1;
2117 break;
2118 }
2119
2120 // Tilt and Orientation
2121 float tilt;
2122 float orientation;
2123 if (mHaveTilt) {
2124 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2125 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2126 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2127 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2128 } else {
2129 tilt = 0;
2130
2131 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002132 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002133 orientation = in.orientation * mOrientationScale;
2134 break;
Michael Wright227c5542020-07-02 18:30:52 +01002135 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002136 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2137 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2138 if (c1 != 0 || c2 != 0) {
2139 orientation = atan2f(c1, c2) * 0.5f;
2140 float confidence = hypotf(c1, c2);
2141 float scale = 1.0f + confidence / 16.0f;
2142 touchMajor *= scale;
2143 touchMinor /= scale;
2144 toolMajor *= scale;
2145 toolMinor /= scale;
2146 } else {
2147 orientation = 0;
2148 }
2149 break;
2150 }
2151 default:
2152 orientation = 0;
2153 }
2154 }
2155
2156 // Distance
2157 float distance;
2158 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002159 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002160 distance = in.distance * mDistanceScale;
2161 break;
2162 default:
2163 distance = 0;
2164 }
2165
2166 // Coverage
2167 int32_t rawLeft, rawTop, rawRight, rawBottom;
2168 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002169 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2171 rawRight = in.toolMinor & 0x0000ffff;
2172 rawBottom = in.toolMajor & 0x0000ffff;
2173 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2174 break;
2175 default:
2176 rawLeft = rawTop = rawRight = rawBottom = 0;
2177 break;
2178 }
2179
2180 // Adjust X,Y coords for device calibration
2181 // TODO: Adjust coverage coords?
2182 float xTransformed = in.x, yTransformed = in.y;
2183 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002184 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185
2186 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002187 float left, top, right, bottom;
2188
2189 switch (mSurfaceOrientation) {
2190 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002191 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2192 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2193 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2194 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2195 orientation -= M_PI_2;
2196 if (mOrientedRanges.haveOrientation &&
2197 orientation < mOrientedRanges.orientation.min) {
2198 orientation +=
2199 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2200 }
2201 break;
2202 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002203 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2204 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2205 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2206 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2207 orientation -= M_PI;
2208 if (mOrientedRanges.haveOrientation &&
2209 orientation < mOrientedRanges.orientation.min) {
2210 orientation +=
2211 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2212 }
2213 break;
2214 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002215 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2216 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2217 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2218 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2219 orientation += M_PI_2;
2220 if (mOrientedRanges.haveOrientation &&
2221 orientation > mOrientedRanges.orientation.max) {
2222 orientation -=
2223 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2224 }
2225 break;
2226 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002227 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2228 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2229 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2230 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2231 break;
2232 }
2233
2234 // Write output coords.
2235 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2236 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002237 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2238 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002239 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2240 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2241 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2242 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2243 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2244 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2245 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002246 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002247 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2248 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2249 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2250 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2251 } else {
2252 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2253 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2254 }
2255
Chris Ye364fdb52020-08-05 15:07:56 -07002256 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002257 uint32_t id = in.id;
2258 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2259 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2260 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2261 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2262 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2263 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2264 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2265 }
2266
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002267 // Write output properties.
2268 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002269 properties.clear();
2270 properties.id = id;
2271 properties.toolType = in.toolType;
2272
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002273 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002274 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002275 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002276 }
2277}
2278
2279void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2280 PointerUsage pointerUsage) {
2281 if (pointerUsage != mPointerUsage) {
2282 abortPointerUsage(when, policyFlags);
2283 mPointerUsage = pointerUsage;
2284 }
2285
2286 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002287 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002288 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2289 break;
Michael Wright227c5542020-07-02 18:30:52 +01002290 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002291 dispatchPointerStylus(when, policyFlags);
2292 break;
Michael Wright227c5542020-07-02 18:30:52 +01002293 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002294 dispatchPointerMouse(when, policyFlags);
2295 break;
Michael Wright227c5542020-07-02 18:30:52 +01002296 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 break;
2298 }
2299}
2300
2301void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2302 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002303 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002304 abortPointerGestures(when, policyFlags);
2305 break;
Michael Wright227c5542020-07-02 18:30:52 +01002306 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002307 abortPointerStylus(when, policyFlags);
2308 break;
Michael Wright227c5542020-07-02 18:30:52 +01002309 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002310 abortPointerMouse(when, policyFlags);
2311 break;
Michael Wright227c5542020-07-02 18:30:52 +01002312 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002313 break;
2314 }
2315
Michael Wright227c5542020-07-02 18:30:52 +01002316 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317}
2318
2319void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2320 // Update current gesture coordinates.
2321 bool cancelPreviousGesture, finishPreviousGesture;
2322 bool sendEvents =
2323 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2324 if (!sendEvents) {
2325 return;
2326 }
2327 if (finishPreviousGesture) {
2328 cancelPreviousGesture = false;
2329 }
2330
2331 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002332 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002333 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002334 if (finishPreviousGesture || cancelPreviousGesture) {
2335 mPointerController->clearSpots();
2336 }
2337
Michael Wright227c5542020-07-02 18:30:52 +01002338 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2340 mPointerGesture.currentGestureIdToIndex,
2341 mPointerGesture.currentGestureIdBits,
2342 mPointerController->getDisplayId());
2343 }
2344 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002345 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002346 }
2347
2348 // Show or hide the pointer if needed.
2349 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002350 case PointerGesture::Mode::NEUTRAL:
2351 case PointerGesture::Mode::QUIET:
2352 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2353 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002355 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 }
2357 break;
Michael Wright227c5542020-07-02 18:30:52 +01002358 case PointerGesture::Mode::TAP:
2359 case PointerGesture::Mode::TAP_DRAG:
2360 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2361 case PointerGesture::Mode::HOVER:
2362 case PointerGesture::Mode::PRESS:
2363 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002364 // Unfade the pointer when the current gesture manipulates the
2365 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002366 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 break;
Michael Wright227c5542020-07-02 18:30:52 +01002368 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 // Fade the pointer when the current gesture manipulates a different
2370 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002371 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002372 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002374 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 }
2376 break;
2377 }
2378
2379 // Send events!
2380 int32_t metaState = getContext()->getGlobalMetaState();
2381 int32_t buttonState = mCurrentCookedState.buttonState;
2382
2383 // Update last coordinates of pointers that have moved so that we observe the new
2384 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002385 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2386 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2387 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2388 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2389 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2390 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 bool moveNeeded = false;
2392 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2393 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2394 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2395 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2396 mPointerGesture.lastGestureIdBits.value);
2397 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2398 mPointerGesture.currentGestureCoords,
2399 mPointerGesture.currentGestureIdToIndex,
2400 mPointerGesture.lastGestureProperties,
2401 mPointerGesture.lastGestureCoords,
2402 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2403 if (buttonState != mLastCookedState.buttonState) {
2404 moveNeeded = true;
2405 }
2406 }
2407
2408 // Send motion events for all pointers that went up or were canceled.
2409 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2410 if (!dispatchedGestureIdBits.isEmpty()) {
2411 if (cancelPreviousGesture) {
2412 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2413 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2414 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2415 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2416 mPointerGesture.downTime);
2417
2418 dispatchedGestureIdBits.clear();
2419 } else {
2420 BitSet32 upGestureIdBits;
2421 if (finishPreviousGesture) {
2422 upGestureIdBits = dispatchedGestureIdBits;
2423 } else {
2424 upGestureIdBits.value =
2425 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2426 }
2427 while (!upGestureIdBits.isEmpty()) {
2428 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2429
2430 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2431 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2432 mPointerGesture.lastGestureProperties,
2433 mPointerGesture.lastGestureCoords,
2434 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2435 0, mPointerGesture.downTime);
2436
2437 dispatchedGestureIdBits.clearBit(id);
2438 }
2439 }
2440 }
2441
2442 // Send motion events for all pointers that moved.
2443 if (moveNeeded) {
2444 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2445 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2446 mPointerGesture.currentGestureProperties,
2447 mPointerGesture.currentGestureCoords,
2448 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2449 mPointerGesture.downTime);
2450 }
2451
2452 // Send motion events for all pointers that went down.
2453 if (down) {
2454 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2455 ~dispatchedGestureIdBits.value);
2456 while (!downGestureIdBits.isEmpty()) {
2457 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2458 dispatchedGestureIdBits.markBit(id);
2459
2460 if (dispatchedGestureIdBits.count() == 1) {
2461 mPointerGesture.downTime = when;
2462 }
2463
2464 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2465 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2466 mPointerGesture.currentGestureCoords,
2467 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2468 0, mPointerGesture.downTime);
2469 }
2470 }
2471
2472 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002473 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2475 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2476 mPointerGesture.currentGestureProperties,
2477 mPointerGesture.currentGestureCoords,
2478 mPointerGesture.currentGestureIdToIndex,
2479 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2480 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2481 // Synthesize a hover move event after all pointers go up to indicate that
2482 // the pointer is hovering again even if the user is not currently touching
2483 // the touch pad. This ensures that a view will receive a fresh hover enter
2484 // event after a tap.
2485 float x, y;
2486 mPointerController->getPosition(&x, &y);
2487
2488 PointerProperties pointerProperties;
2489 pointerProperties.clear();
2490 pointerProperties.id = 0;
2491 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2492
2493 PointerCoords pointerCoords;
2494 pointerCoords.clear();
2495 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2496 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2497
2498 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002499 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2500 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2501 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2502 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2503 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 getListener()->notifyMotion(&args);
2505 }
2506
2507 // Update state.
2508 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2509 if (!down) {
2510 mPointerGesture.lastGestureIdBits.clear();
2511 } else {
2512 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2513 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2514 uint32_t id = idBits.clearFirstMarkedBit();
2515 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2516 mPointerGesture.lastGestureProperties[index].copyFrom(
2517 mPointerGesture.currentGestureProperties[index]);
2518 mPointerGesture.lastGestureCoords[index].copyFrom(
2519 mPointerGesture.currentGestureCoords[index]);
2520 mPointerGesture.lastGestureIdToIndex[id] = index;
2521 }
2522 }
2523}
2524
2525void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2526 // Cancel previously dispatches pointers.
2527 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2528 int32_t metaState = getContext()->getGlobalMetaState();
2529 int32_t buttonState = mCurrentRawState.buttonState;
2530 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2531 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2532 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2533 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2534 0, 0, mPointerGesture.downTime);
2535 }
2536
2537 // Reset the current pointer gesture.
2538 mPointerGesture.reset();
2539 mPointerVelocityControl.reset();
2540
2541 // Remove any current spots.
2542 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002543 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 mPointerController->clearSpots();
2545 }
2546}
2547
2548bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2549 bool* outFinishPreviousGesture, bool isTimeout) {
2550 *outCancelPreviousGesture = false;
2551 *outFinishPreviousGesture = false;
2552
2553 // Handle TAP timeout.
2554 if (isTimeout) {
2555#if DEBUG_GESTURES
2556 ALOGD("Gestures: Processing timeout");
2557#endif
2558
Michael Wright227c5542020-07-02 18:30:52 +01002559 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002560 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2561 // The tap/drag timeout has not yet expired.
2562 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2563 mConfig.pointerGestureTapDragInterval);
2564 } else {
2565 // The tap is finished.
2566#if DEBUG_GESTURES
2567 ALOGD("Gestures: TAP finished");
2568#endif
2569 *outFinishPreviousGesture = true;
2570
2571 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002572 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002573 mPointerGesture.currentGestureIdBits.clear();
2574
2575 mPointerVelocityControl.reset();
2576 return true;
2577 }
2578 }
2579
2580 // We did not handle this timeout.
2581 return false;
2582 }
2583
2584 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2585 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2586
2587 // Update the velocity tracker.
2588 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002589 std::vector<VelocityTracker::Position> positions;
2590 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591 uint32_t id = idBits.clearFirstMarkedBit();
2592 const RawPointerData::Pointer& pointer =
2593 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002594 float x = pointer.x * mPointerXMovementScale;
2595 float y = pointer.y * mPointerYMovementScale;
2596 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002597 }
2598 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2599 positions);
2600 }
2601
2602 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2603 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002604 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2605 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2606 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002607 mPointerGesture.resetTap();
2608 }
2609
2610 // Pick a new active touch id if needed.
2611 // Choose an arbitrary pointer that just went down, if there is one.
2612 // Otherwise choose an arbitrary remaining pointer.
2613 // This guarantees we always have an active touch id when there is at least one pointer.
2614 // We keep the same active touch id for as long as possible.
2615 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2616 int32_t activeTouchId = lastActiveTouchId;
2617 if (activeTouchId < 0) {
2618 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2619 activeTouchId = mPointerGesture.activeTouchId =
2620 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2621 mPointerGesture.firstTouchTime = when;
2622 }
2623 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2624 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2625 activeTouchId = mPointerGesture.activeTouchId =
2626 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2627 } else {
2628 activeTouchId = mPointerGesture.activeTouchId = -1;
2629 }
2630 }
2631
2632 // Determine whether we are in quiet time.
2633 bool isQuietTime = false;
2634 if (activeTouchId < 0) {
2635 mPointerGesture.resetQuietTime();
2636 } else {
2637 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2638 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002639 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2640 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2641 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002642 currentFingerCount < 2) {
2643 // Enter quiet time when exiting swipe or freeform state.
2644 // This is to prevent accidentally entering the hover state and flinging the
2645 // pointer when finishing a swipe and there is still one pointer left onscreen.
2646 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002647 } else if (mPointerGesture.lastGestureMode ==
2648 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002649 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2650 // Enter quiet time when releasing the button and there are still two or more
2651 // fingers down. This may indicate that one finger was used to press the button
2652 // but it has not gone up yet.
2653 isQuietTime = true;
2654 }
2655 if (isQuietTime) {
2656 mPointerGesture.quietTime = when;
2657 }
2658 }
2659 }
2660
2661 // Switch states based on button and pointer state.
2662 if (isQuietTime) {
2663 // Case 1: Quiet time. (QUIET)
2664#if DEBUG_GESTURES
2665 ALOGD("Gestures: QUIET for next %0.3fms",
2666 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2667#endif
Michael Wright227c5542020-07-02 18:30:52 +01002668 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002669 *outFinishPreviousGesture = true;
2670 }
2671
2672 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002673 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002674 mPointerGesture.currentGestureIdBits.clear();
2675
2676 mPointerVelocityControl.reset();
2677 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2678 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2679 // The pointer follows the active touch point.
2680 // Emit DOWN, MOVE, UP events at the pointer location.
2681 //
2682 // Only the active touch matters; other fingers are ignored. This policy helps
2683 // to handle the case where the user places a second finger on the touch pad
2684 // to apply the necessary force to depress an integrated button below the surface.
2685 // We don't want the second finger to be delivered to applications.
2686 //
2687 // For this to work well, we need to make sure to track the pointer that is really
2688 // active. If the user first puts one finger down to click then adds another
2689 // finger to drag then the active pointer should switch to the finger that is
2690 // being dragged.
2691#if DEBUG_GESTURES
2692 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2693 "currentFingerCount=%d",
2694 activeTouchId, currentFingerCount);
2695#endif
2696 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002697 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002698 *outFinishPreviousGesture = true;
2699 mPointerGesture.activeGestureId = 0;
2700 }
2701
2702 // Switch pointers if needed.
2703 // Find the fastest pointer and follow it.
2704 if (activeTouchId >= 0 && currentFingerCount > 1) {
2705 int32_t bestId = -1;
2706 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2707 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2708 uint32_t id = idBits.clearFirstMarkedBit();
2709 float vx, vy;
2710 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2711 float speed = hypotf(vx, vy);
2712 if (speed > bestSpeed) {
2713 bestId = id;
2714 bestSpeed = speed;
2715 }
2716 }
2717 }
2718 if (bestId >= 0 && bestId != activeTouchId) {
2719 mPointerGesture.activeTouchId = activeTouchId = bestId;
2720#if DEBUG_GESTURES
2721 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2722 "bestId=%d, bestSpeed=%0.3f",
2723 bestId, bestSpeed);
2724#endif
2725 }
2726 }
2727
2728 float deltaX = 0, deltaY = 0;
2729 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2730 const RawPointerData::Pointer& currentPointer =
2731 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2732 const RawPointerData::Pointer& lastPointer =
2733 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2734 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2735 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2736
2737 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2738 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2739
2740 // Move the pointer using a relative motion.
2741 // When using spots, the click will occur at the position of the anchor
2742 // spot and all other spots will move there.
2743 mPointerController->move(deltaX, deltaY);
2744 } else {
2745 mPointerVelocityControl.reset();
2746 }
2747
2748 float x, y;
2749 mPointerController->getPosition(&x, &y);
2750
Michael Wright227c5542020-07-02 18:30:52 +01002751 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002752 mPointerGesture.currentGestureIdBits.clear();
2753 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2754 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2755 mPointerGesture.currentGestureProperties[0].clear();
2756 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2757 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2758 mPointerGesture.currentGestureCoords[0].clear();
2759 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2760 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2761 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2762 } else if (currentFingerCount == 0) {
2763 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002764 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002765 *outFinishPreviousGesture = true;
2766 }
2767
2768 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2769 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2770 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002771 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2772 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002773 lastFingerCount == 1) {
2774 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2775 float x, y;
2776 mPointerController->getPosition(&x, &y);
2777 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2778 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2779#if DEBUG_GESTURES
2780 ALOGD("Gestures: TAP");
2781#endif
2782
2783 mPointerGesture.tapUpTime = when;
2784 getContext()->requestTimeoutAtTime(when +
2785 mConfig.pointerGestureTapDragInterval);
2786
2787 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002788 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 mPointerGesture.currentGestureIdBits.clear();
2790 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2791 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2792 mPointerGesture.currentGestureProperties[0].clear();
2793 mPointerGesture.currentGestureProperties[0].id =
2794 mPointerGesture.activeGestureId;
2795 mPointerGesture.currentGestureProperties[0].toolType =
2796 AMOTION_EVENT_TOOL_TYPE_FINGER;
2797 mPointerGesture.currentGestureCoords[0].clear();
2798 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2799 mPointerGesture.tapX);
2800 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2801 mPointerGesture.tapY);
2802 mPointerGesture.currentGestureCoords[0]
2803 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2804
2805 tapped = true;
2806 } else {
2807#if DEBUG_GESTURES
2808 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2809 y - mPointerGesture.tapY);
2810#endif
2811 }
2812 } else {
2813#if DEBUG_GESTURES
2814 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2815 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2816 (when - mPointerGesture.tapDownTime) * 0.000001f);
2817 } else {
2818 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2819 }
2820#endif
2821 }
2822 }
2823
2824 mPointerVelocityControl.reset();
2825
2826 if (!tapped) {
2827#if DEBUG_GESTURES
2828 ALOGD("Gestures: NEUTRAL");
2829#endif
2830 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002831 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002832 mPointerGesture.currentGestureIdBits.clear();
2833 }
2834 } else if (currentFingerCount == 1) {
2835 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2836 // The pointer follows the active touch point.
2837 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2838 // When in TAP_DRAG, emit MOVE events at the pointer location.
2839 ALOG_ASSERT(activeTouchId >= 0);
2840
Michael Wright227c5542020-07-02 18:30:52 +01002841 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2842 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002843 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2844 float x, y;
2845 mPointerController->getPosition(&x, &y);
2846 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2847 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002848 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 } else {
2850#if DEBUG_GESTURES
2851 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2852 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2853#endif
2854 }
2855 } else {
2856#if DEBUG_GESTURES
2857 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2858 (when - mPointerGesture.tapUpTime) * 0.000001f);
2859#endif
2860 }
Michael Wright227c5542020-07-02 18:30:52 +01002861 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2862 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002863 }
2864
2865 float deltaX = 0, deltaY = 0;
2866 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2867 const RawPointerData::Pointer& currentPointer =
2868 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2869 const RawPointerData::Pointer& lastPointer =
2870 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2871 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2872 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2873
2874 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2875 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2876
2877 // Move the pointer using a relative motion.
2878 // When using spots, the hover or drag will occur at the position of the anchor spot.
2879 mPointerController->move(deltaX, deltaY);
2880 } else {
2881 mPointerVelocityControl.reset();
2882 }
2883
2884 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002885 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886#if DEBUG_GESTURES
2887 ALOGD("Gestures: TAP_DRAG");
2888#endif
2889 down = true;
2890 } else {
2891#if DEBUG_GESTURES
2892 ALOGD("Gestures: HOVER");
2893#endif
Michael Wright227c5542020-07-02 18:30:52 +01002894 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 *outFinishPreviousGesture = true;
2896 }
2897 mPointerGesture.activeGestureId = 0;
2898 down = false;
2899 }
2900
2901 float x, y;
2902 mPointerController->getPosition(&x, &y);
2903
2904 mPointerGesture.currentGestureIdBits.clear();
2905 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2906 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2907 mPointerGesture.currentGestureProperties[0].clear();
2908 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2909 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2910 mPointerGesture.currentGestureCoords[0].clear();
2911 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2912 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2913 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2914 down ? 1.0f : 0.0f);
2915
2916 if (lastFingerCount == 0 && currentFingerCount != 0) {
2917 mPointerGesture.resetTap();
2918 mPointerGesture.tapDownTime = when;
2919 mPointerGesture.tapX = x;
2920 mPointerGesture.tapY = y;
2921 }
2922 } else {
2923 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2924 // We need to provide feedback for each finger that goes down so we cannot wait
2925 // for the fingers to move before deciding what to do.
2926 //
2927 // The ambiguous case is deciding what to do when there are two fingers down but they
2928 // have not moved enough to determine whether they are part of a drag or part of a
2929 // freeform gesture, or just a press or long-press at the pointer location.
2930 //
2931 // When there are two fingers we start with the PRESS hypothesis and we generate a
2932 // down at the pointer location.
2933 //
2934 // When the two fingers move enough or when additional fingers are added, we make
2935 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2936 ALOG_ASSERT(activeTouchId >= 0);
2937
2938 bool settled = when >=
2939 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002940 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2941 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2942 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943 *outFinishPreviousGesture = true;
2944 } else if (!settled && currentFingerCount > lastFingerCount) {
2945 // Additional pointers have gone down but not yet settled.
2946 // Reset the gesture.
2947#if DEBUG_GESTURES
2948 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2949 "settle time remaining %0.3fms",
2950 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2951 when) * 0.000001f);
2952#endif
2953 *outCancelPreviousGesture = true;
2954 } else {
2955 // Continue previous gesture.
2956 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2957 }
2958
2959 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002960 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002961 mPointerGesture.activeGestureId = 0;
2962 mPointerGesture.referenceIdBits.clear();
2963 mPointerVelocityControl.reset();
2964
2965 // Use the centroid and pointer location as the reference points for the gesture.
2966#if DEBUG_GESTURES
2967 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2968 "settle time remaining %0.3fms",
2969 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2970 when) * 0.000001f);
2971#endif
2972 mCurrentRawState.rawPointerData
2973 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
2974 &mPointerGesture.referenceTouchY);
2975 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
2976 &mPointerGesture.referenceGestureY);
2977 }
2978
2979 // Clear the reference deltas for fingers not yet included in the reference calculation.
2980 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
2981 ~mPointerGesture.referenceIdBits.value);
2982 !idBits.isEmpty();) {
2983 uint32_t id = idBits.clearFirstMarkedBit();
2984 mPointerGesture.referenceDeltas[id].dx = 0;
2985 mPointerGesture.referenceDeltas[id].dy = 0;
2986 }
2987 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
2988
2989 // Add delta for all fingers and calculate a common movement delta.
2990 float commonDeltaX = 0, commonDeltaY = 0;
2991 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
2992 mCurrentCookedState.fingerIdBits.value);
2993 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
2994 bool first = (idBits == commonIdBits);
2995 uint32_t id = idBits.clearFirstMarkedBit();
2996 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
2997 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
2998 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
2999 delta.dx += cpd.x - lpd.x;
3000 delta.dy += cpd.y - lpd.y;
3001
3002 if (first) {
3003 commonDeltaX = delta.dx;
3004 commonDeltaY = delta.dy;
3005 } else {
3006 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3007 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3008 }
3009 }
3010
3011 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003012 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003013 float dist[MAX_POINTER_ID + 1];
3014 int32_t distOverThreshold = 0;
3015 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3016 uint32_t id = idBits.clearFirstMarkedBit();
3017 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3018 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3019 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3020 distOverThreshold += 1;
3021 }
3022 }
3023
3024 // Only transition when at least two pointers have moved further than
3025 // the minimum distance threshold.
3026 if (distOverThreshold >= 2) {
3027 if (currentFingerCount > 2) {
3028 // There are more than two pointers, switch to FREEFORM.
3029#if DEBUG_GESTURES
3030 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3031 currentFingerCount);
3032#endif
3033 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003034 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003035 } else {
3036 // There are exactly two pointers.
3037 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3038 uint32_t id1 = idBits.clearFirstMarkedBit();
3039 uint32_t id2 = idBits.firstMarkedBit();
3040 const RawPointerData::Pointer& p1 =
3041 mCurrentRawState.rawPointerData.pointerForId(id1);
3042 const RawPointerData::Pointer& p2 =
3043 mCurrentRawState.rawPointerData.pointerForId(id2);
3044 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3045 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3046 // There are two pointers but they are too far apart for a SWIPE,
3047 // switch to FREEFORM.
3048#if DEBUG_GESTURES
3049 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3050 mutualDistance, mPointerGestureMaxSwipeWidth);
3051#endif
3052 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003053 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003054 } else {
3055 // There are two pointers. Wait for both pointers to start moving
3056 // before deciding whether this is a SWIPE or FREEFORM gesture.
3057 float dist1 = dist[id1];
3058 float dist2 = dist[id2];
3059 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3060 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3061 // Calculate the dot product of the displacement vectors.
3062 // When the vectors are oriented in approximately the same direction,
3063 // the angle betweeen them is near zero and the cosine of the angle
3064 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3065 // mag(v2).
3066 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3067 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3068 float dx1 = delta1.dx * mPointerXZoomScale;
3069 float dy1 = delta1.dy * mPointerYZoomScale;
3070 float dx2 = delta2.dx * mPointerXZoomScale;
3071 float dy2 = delta2.dy * mPointerYZoomScale;
3072 float dot = dx1 * dx2 + dy1 * dy2;
3073 float cosine = dot / (dist1 * dist2); // denominator always > 0
3074 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3075 // Pointers are moving in the same direction. Switch to SWIPE.
3076#if DEBUG_GESTURES
3077 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3078 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3079 "cosine %0.3f >= %0.3f",
3080 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3081 mConfig.pointerGestureMultitouchMinDistance, cosine,
3082 mConfig.pointerGestureSwipeTransitionAngleCosine);
3083#endif
Michael Wright227c5542020-07-02 18:30:52 +01003084 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003085 } else {
3086 // Pointers are moving in different directions. Switch to FREEFORM.
3087#if DEBUG_GESTURES
3088 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3089 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3090 "cosine %0.3f < %0.3f",
3091 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3092 mConfig.pointerGestureMultitouchMinDistance, cosine,
3093 mConfig.pointerGestureSwipeTransitionAngleCosine);
3094#endif
3095 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003096 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003097 }
3098 }
3099 }
3100 }
3101 }
Michael Wright227c5542020-07-02 18:30:52 +01003102 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003103 // Switch from SWIPE to FREEFORM if additional pointers go down.
3104 // Cancel previous gesture.
3105 if (currentFingerCount > 2) {
3106#if DEBUG_GESTURES
3107 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3108 currentFingerCount);
3109#endif
3110 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003111 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003112 }
3113 }
3114
3115 // Move the reference points based on the overall group motion of the fingers
3116 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003117 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003118 (commonDeltaX || commonDeltaY)) {
3119 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3120 uint32_t id = idBits.clearFirstMarkedBit();
3121 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3122 delta.dx = 0;
3123 delta.dy = 0;
3124 }
3125
3126 mPointerGesture.referenceTouchX += commonDeltaX;
3127 mPointerGesture.referenceTouchY += commonDeltaY;
3128
3129 commonDeltaX *= mPointerXMovementScale;
3130 commonDeltaY *= mPointerYMovementScale;
3131
3132 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3133 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3134
3135 mPointerGesture.referenceGestureX += commonDeltaX;
3136 mPointerGesture.referenceGestureY += commonDeltaY;
3137 }
3138
3139 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003140 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3141 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003142 // PRESS or SWIPE mode.
3143#if DEBUG_GESTURES
3144 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3145 "activeGestureId=%d, currentTouchPointerCount=%d",
3146 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3147#endif
3148 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3149
3150 mPointerGesture.currentGestureIdBits.clear();
3151 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3152 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3153 mPointerGesture.currentGestureProperties[0].clear();
3154 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3155 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3156 mPointerGesture.currentGestureCoords[0].clear();
3157 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3158 mPointerGesture.referenceGestureX);
3159 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3160 mPointerGesture.referenceGestureY);
3161 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003162 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003163 // FREEFORM mode.
3164#if DEBUG_GESTURES
3165 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3166 "activeGestureId=%d, currentTouchPointerCount=%d",
3167 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3168#endif
3169 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3170
3171 mPointerGesture.currentGestureIdBits.clear();
3172
3173 BitSet32 mappedTouchIdBits;
3174 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003175 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003176 // Initially, assign the active gesture id to the active touch point
3177 // if there is one. No other touch id bits are mapped yet.
3178 if (!*outCancelPreviousGesture) {
3179 mappedTouchIdBits.markBit(activeTouchId);
3180 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3181 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3182 mPointerGesture.activeGestureId;
3183 } else {
3184 mPointerGesture.activeGestureId = -1;
3185 }
3186 } else {
3187 // Otherwise, assume we mapped all touches from the previous frame.
3188 // Reuse all mappings that are still applicable.
3189 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3190 mCurrentCookedState.fingerIdBits.value;
3191 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3192
3193 // Check whether we need to choose a new active gesture id because the
3194 // current went went up.
3195 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3196 ~mCurrentCookedState.fingerIdBits.value);
3197 !upTouchIdBits.isEmpty();) {
3198 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3199 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3200 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3201 mPointerGesture.activeGestureId = -1;
3202 break;
3203 }
3204 }
3205 }
3206
3207#if DEBUG_GESTURES
3208 ALOGD("Gestures: FREEFORM follow up "
3209 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3210 "activeGestureId=%d",
3211 mappedTouchIdBits.value, usedGestureIdBits.value,
3212 mPointerGesture.activeGestureId);
3213#endif
3214
3215 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3216 for (uint32_t i = 0; i < currentFingerCount; i++) {
3217 uint32_t touchId = idBits.clearFirstMarkedBit();
3218 uint32_t gestureId;
3219 if (!mappedTouchIdBits.hasBit(touchId)) {
3220 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3221 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3222#if DEBUG_GESTURES
3223 ALOGD("Gestures: FREEFORM "
3224 "new mapping for touch id %d -> gesture id %d",
3225 touchId, gestureId);
3226#endif
3227 } else {
3228 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3229#if DEBUG_GESTURES
3230 ALOGD("Gestures: FREEFORM "
3231 "existing mapping for touch id %d -> gesture id %d",
3232 touchId, gestureId);
3233#endif
3234 }
3235 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3236 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3237
3238 const RawPointerData::Pointer& pointer =
3239 mCurrentRawState.rawPointerData.pointerForId(touchId);
3240 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3241 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3242 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3243
3244 mPointerGesture.currentGestureProperties[i].clear();
3245 mPointerGesture.currentGestureProperties[i].id = gestureId;
3246 mPointerGesture.currentGestureProperties[i].toolType =
3247 AMOTION_EVENT_TOOL_TYPE_FINGER;
3248 mPointerGesture.currentGestureCoords[i].clear();
3249 mPointerGesture.currentGestureCoords[i]
3250 .setAxisValue(AMOTION_EVENT_AXIS_X,
3251 mPointerGesture.referenceGestureX + deltaX);
3252 mPointerGesture.currentGestureCoords[i]
3253 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3254 mPointerGesture.referenceGestureY + deltaY);
3255 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3256 1.0f);
3257 }
3258
3259 if (mPointerGesture.activeGestureId < 0) {
3260 mPointerGesture.activeGestureId =
3261 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3262#if DEBUG_GESTURES
3263 ALOGD("Gestures: FREEFORM new "
3264 "activeGestureId=%d",
3265 mPointerGesture.activeGestureId);
3266#endif
3267 }
3268 }
3269 }
3270
3271 mPointerController->setButtonState(mCurrentRawState.buttonState);
3272
3273#if DEBUG_GESTURES
3274 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3275 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3276 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3277 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3278 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3279 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3280 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3281 uint32_t id = idBits.clearFirstMarkedBit();
3282 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3283 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3284 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3285 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3286 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3287 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3288 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3289 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3290 }
3291 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3292 uint32_t id = idBits.clearFirstMarkedBit();
3293 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3294 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3295 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3296 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3297 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3298 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3299 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3300 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3301 }
3302#endif
3303 return true;
3304}
3305
3306void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3307 mPointerSimple.currentCoords.clear();
3308 mPointerSimple.currentProperties.clear();
3309
3310 bool down, hovering;
3311 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3312 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3313 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3314 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3315 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3316 mPointerController->setPosition(x, y);
3317
3318 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3319 down = !hovering;
3320
3321 mPointerController->getPosition(&x, &y);
3322 mPointerSimple.currentCoords.copyFrom(
3323 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3324 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3325 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3326 mPointerSimple.currentProperties.id = 0;
3327 mPointerSimple.currentProperties.toolType =
3328 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3329 } else {
3330 down = false;
3331 hovering = false;
3332 }
3333
3334 dispatchPointerSimple(when, policyFlags, down, hovering);
3335}
3336
3337void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3338 abortPointerSimple(when, policyFlags);
3339}
3340
3341void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3342 mPointerSimple.currentCoords.clear();
3343 mPointerSimple.currentProperties.clear();
3344
3345 bool down, hovering;
3346 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3347 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3348 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3349 float deltaX = 0, deltaY = 0;
3350 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3351 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3352 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3353 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3354 mPointerXMovementScale;
3355 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3356 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3357 mPointerYMovementScale;
3358
3359 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3360 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3361
3362 mPointerController->move(deltaX, deltaY);
3363 } else {
3364 mPointerVelocityControl.reset();
3365 }
3366
3367 down = isPointerDown(mCurrentRawState.buttonState);
3368 hovering = !down;
3369
3370 float x, y;
3371 mPointerController->getPosition(&x, &y);
3372 mPointerSimple.currentCoords.copyFrom(
3373 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3374 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3375 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3376 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3377 hovering ? 0.0f : 1.0f);
3378 mPointerSimple.currentProperties.id = 0;
3379 mPointerSimple.currentProperties.toolType =
3380 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3381 } else {
3382 mPointerVelocityControl.reset();
3383
3384 down = false;
3385 hovering = false;
3386 }
3387
3388 dispatchPointerSimple(when, policyFlags, down, hovering);
3389}
3390
3391void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3392 abortPointerSimple(when, policyFlags);
3393
3394 mPointerVelocityControl.reset();
3395}
3396
3397void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3398 bool hovering) {
3399 int32_t metaState = getContext()->getGlobalMetaState();
3400 int32_t displayId = mViewport.displayId;
3401
3402 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003403 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003404 mPointerController->clearSpots();
3405 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003406 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003407 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003408 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003409 }
3410 displayId = mPointerController->getDisplayId();
3411
3412 float xCursorPosition;
3413 float yCursorPosition;
3414 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3415
3416 if (mPointerSimple.down && !down) {
3417 mPointerSimple.down = false;
3418
3419 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003420 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3421 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003422 mLastRawState.buttonState, MotionClassification::NONE,
3423 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3424 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3425 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3426 /* videoFrames */ {});
3427 getListener()->notifyMotion(&args);
3428 }
3429
3430 if (mPointerSimple.hovering && !hovering) {
3431 mPointerSimple.hovering = false;
3432
3433 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003434 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3435 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3436 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003437 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3438 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3439 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3440 /* videoFrames */ {});
3441 getListener()->notifyMotion(&args);
3442 }
3443
3444 if (down) {
3445 if (!mPointerSimple.down) {
3446 mPointerSimple.down = true;
3447 mPointerSimple.downTime = when;
3448
3449 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003450 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003451 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3452 metaState, mCurrentRawState.buttonState,
3453 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3454 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3455 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3456 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3457 getListener()->notifyMotion(&args);
3458 }
3459
3460 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003461 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3462 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003463 mCurrentRawState.buttonState, MotionClassification::NONE,
3464 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3465 &mPointerSimple.currentCoords, mOrientedXPrecision,
3466 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3467 mPointerSimple.downTime, /* videoFrames */ {});
3468 getListener()->notifyMotion(&args);
3469 }
3470
3471 if (hovering) {
3472 if (!mPointerSimple.hovering) {
3473 mPointerSimple.hovering = true;
3474
3475 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003476 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003477 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3478 metaState, mCurrentRawState.buttonState,
3479 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3480 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3481 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3482 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3483 getListener()->notifyMotion(&args);
3484 }
3485
3486 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003487 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3488 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3489 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003490 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3491 &mPointerSimple.currentCoords, mOrientedXPrecision,
3492 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3493 mPointerSimple.downTime, /* videoFrames */ {});
3494 getListener()->notifyMotion(&args);
3495 }
3496
3497 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3498 float vscroll = mCurrentRawState.rawVScroll;
3499 float hscroll = mCurrentRawState.rawHScroll;
3500 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3501 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3502
3503 // Send scroll.
3504 PointerCoords pointerCoords;
3505 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3506 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3507 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3508
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003509 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3510 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003511 mCurrentRawState.buttonState, MotionClassification::NONE,
3512 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3513 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3514 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3515 /* videoFrames */ {});
3516 getListener()->notifyMotion(&args);
3517 }
3518
3519 // Save state.
3520 if (down || hovering) {
3521 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3522 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3523 } else {
3524 mPointerSimple.reset();
3525 }
3526}
3527
3528void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3529 mPointerSimple.currentCoords.clear();
3530 mPointerSimple.currentProperties.clear();
3531
3532 dispatchPointerSimple(when, policyFlags, false, false);
3533}
3534
3535void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3536 int32_t action, int32_t actionButton, int32_t flags,
3537 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3538 const PointerProperties* properties,
3539 const PointerCoords* coords, const uint32_t* idToIndex,
3540 BitSet32 idBits, int32_t changedId, float xPrecision,
3541 float yPrecision, nsecs_t downTime) {
3542 PointerCoords pointerCoords[MAX_POINTERS];
3543 PointerProperties pointerProperties[MAX_POINTERS];
3544 uint32_t pointerCount = 0;
3545 while (!idBits.isEmpty()) {
3546 uint32_t id = idBits.clearFirstMarkedBit();
3547 uint32_t index = idToIndex[id];
3548 pointerProperties[pointerCount].copyFrom(properties[index]);
3549 pointerCoords[pointerCount].copyFrom(coords[index]);
3550
3551 if (changedId >= 0 && id == uint32_t(changedId)) {
3552 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3553 }
3554
3555 pointerCount += 1;
3556 }
3557
3558 ALOG_ASSERT(pointerCount != 0);
3559
3560 if (changedId >= 0 && pointerCount == 1) {
3561 // Replace initial down and final up action.
3562 // We can compare the action without masking off the changed pointer index
3563 // because we know the index is 0.
3564 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3565 action = AMOTION_EVENT_ACTION_DOWN;
3566 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003567 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3568 action = AMOTION_EVENT_ACTION_CANCEL;
3569 } else {
3570 action = AMOTION_EVENT_ACTION_UP;
3571 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572 } else {
3573 // Can't happen.
3574 ALOG_ASSERT(false);
3575 }
3576 }
3577 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3578 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003579 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003580 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3581 }
3582 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3583 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003584 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003585 std::for_each(frames.begin(), frames.end(),
3586 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003587 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3588 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3590 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3591 downTime, std::move(frames));
3592 getListener()->notifyMotion(&args);
3593}
3594
3595bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3596 const PointerCoords* inCoords,
3597 const uint32_t* inIdToIndex,
3598 PointerProperties* outProperties,
3599 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3600 BitSet32 idBits) const {
3601 bool changed = false;
3602 while (!idBits.isEmpty()) {
3603 uint32_t id = idBits.clearFirstMarkedBit();
3604 uint32_t inIndex = inIdToIndex[id];
3605 uint32_t outIndex = outIdToIndex[id];
3606
3607 const PointerProperties& curInProperties = inProperties[inIndex];
3608 const PointerCoords& curInCoords = inCoords[inIndex];
3609 PointerProperties& curOutProperties = outProperties[outIndex];
3610 PointerCoords& curOutCoords = outCoords[outIndex];
3611
3612 if (curInProperties != curOutProperties) {
3613 curOutProperties.copyFrom(curInProperties);
3614 changed = true;
3615 }
3616
3617 if (curInCoords != curOutCoords) {
3618 curOutCoords.copyFrom(curInCoords);
3619 changed = true;
3620 }
3621 }
3622 return changed;
3623}
3624
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003625void TouchInputMapper::cancelTouch(nsecs_t when) {
3626 abortPointerUsage(when, 0 /*policyFlags*/);
3627 abortTouches(when, 0 /* policyFlags*/);
3628}
3629
Arthur Hung4197f6b2020-03-16 15:39:59 +08003630// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003631void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003632 // Scale to surface coordinate.
3633 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3634 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3635
3636 // Rotate to surface coordinate.
3637 // 0 - no swap and reverse.
3638 // 90 - swap x/y and reverse y.
3639 // 180 - reverse x, y.
3640 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003641 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003642 case DISPLAY_ORIENTATION_0:
3643 x = xScaled + mXTranslate;
3644 y = yScaled + mYTranslate;
3645 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003646 case DISPLAY_ORIENTATION_90:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003647 y = mSurfaceRight - xScaled;
3648 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003649 break;
3650 case DISPLAY_ORIENTATION_180:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003651 x = mSurfaceRight - xScaled;
3652 y = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003653 break;
3654 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003655 y = xScaled + mXTranslate;
3656 x = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003657 break;
3658 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003659 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003660 }
3661}
3662
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003663bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003664 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3665 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3666
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003667 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003668 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003669 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003670 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003671}
3672
3673const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3674 for (const VirtualKey& virtualKey : mVirtualKeys) {
3675#if DEBUG_VIRTUAL_KEYS
3676 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3677 "left=%d, top=%d, right=%d, bottom=%d",
3678 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3679 virtualKey.hitRight, virtualKey.hitBottom);
3680#endif
3681
3682 if (virtualKey.isHit(x, y)) {
3683 return &virtualKey;
3684 }
3685 }
3686
3687 return nullptr;
3688}
3689
3690void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3691 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3692 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3693
3694 current->rawPointerData.clearIdBits();
3695
3696 if (currentPointerCount == 0) {
3697 // No pointers to assign.
3698 return;
3699 }
3700
3701 if (lastPointerCount == 0) {
3702 // All pointers are new.
3703 for (uint32_t i = 0; i < currentPointerCount; i++) {
3704 uint32_t id = i;
3705 current->rawPointerData.pointers[i].id = id;
3706 current->rawPointerData.idToIndex[id] = i;
3707 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3708 }
3709 return;
3710 }
3711
3712 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3713 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3714 // Only one pointer and no change in count so it must have the same id as before.
3715 uint32_t id = last->rawPointerData.pointers[0].id;
3716 current->rawPointerData.pointers[0].id = id;
3717 current->rawPointerData.idToIndex[id] = 0;
3718 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3719 return;
3720 }
3721
3722 // General case.
3723 // We build a heap of squared euclidean distances between current and last pointers
3724 // associated with the current and last pointer indices. Then, we find the best
3725 // match (by distance) for each current pointer.
3726 // The pointers must have the same tool type but it is possible for them to
3727 // transition from hovering to touching or vice-versa while retaining the same id.
3728 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3729
3730 uint32_t heapSize = 0;
3731 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3732 currentPointerIndex++) {
3733 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3734 lastPointerIndex++) {
3735 const RawPointerData::Pointer& currentPointer =
3736 current->rawPointerData.pointers[currentPointerIndex];
3737 const RawPointerData::Pointer& lastPointer =
3738 last->rawPointerData.pointers[lastPointerIndex];
3739 if (currentPointer.toolType == lastPointer.toolType) {
3740 int64_t deltaX = currentPointer.x - lastPointer.x;
3741 int64_t deltaY = currentPointer.y - lastPointer.y;
3742
3743 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3744
3745 // Insert new element into the heap (sift up).
3746 heap[heapSize].currentPointerIndex = currentPointerIndex;
3747 heap[heapSize].lastPointerIndex = lastPointerIndex;
3748 heap[heapSize].distance = distance;
3749 heapSize += 1;
3750 }
3751 }
3752 }
3753
3754 // Heapify
3755 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3756 startIndex -= 1;
3757 for (uint32_t parentIndex = startIndex;;) {
3758 uint32_t childIndex = parentIndex * 2 + 1;
3759 if (childIndex >= heapSize) {
3760 break;
3761 }
3762
3763 if (childIndex + 1 < heapSize &&
3764 heap[childIndex + 1].distance < heap[childIndex].distance) {
3765 childIndex += 1;
3766 }
3767
3768 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3769 break;
3770 }
3771
3772 swap(heap[parentIndex], heap[childIndex]);
3773 parentIndex = childIndex;
3774 }
3775 }
3776
3777#if DEBUG_POINTER_ASSIGNMENT
3778 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3779 for (size_t i = 0; i < heapSize; i++) {
3780 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3781 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3782 }
3783#endif
3784
3785 // Pull matches out by increasing order of distance.
3786 // To avoid reassigning pointers that have already been matched, the loop keeps track
3787 // of which last and current pointers have been matched using the matchedXXXBits variables.
3788 // It also tracks the used pointer id bits.
3789 BitSet32 matchedLastBits(0);
3790 BitSet32 matchedCurrentBits(0);
3791 BitSet32 usedIdBits(0);
3792 bool first = true;
3793 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3794 while (heapSize > 0) {
3795 if (first) {
3796 // The first time through the loop, we just consume the root element of
3797 // the heap (the one with smallest distance).
3798 first = false;
3799 } else {
3800 // Previous iterations consumed the root element of the heap.
3801 // Pop root element off of the heap (sift down).
3802 heap[0] = heap[heapSize];
3803 for (uint32_t parentIndex = 0;;) {
3804 uint32_t childIndex = parentIndex * 2 + 1;
3805 if (childIndex >= heapSize) {
3806 break;
3807 }
3808
3809 if (childIndex + 1 < heapSize &&
3810 heap[childIndex + 1].distance < heap[childIndex].distance) {
3811 childIndex += 1;
3812 }
3813
3814 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3815 break;
3816 }
3817
3818 swap(heap[parentIndex], heap[childIndex]);
3819 parentIndex = childIndex;
3820 }
3821
3822#if DEBUG_POINTER_ASSIGNMENT
3823 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003824 for (size_t j = 0; j < heapSize; j++) {
3825 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3826 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003827 }
3828#endif
3829 }
3830
3831 heapSize -= 1;
3832
3833 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3834 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3835
3836 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3837 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3838
3839 matchedCurrentBits.markBit(currentPointerIndex);
3840 matchedLastBits.markBit(lastPointerIndex);
3841
3842 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3843 current->rawPointerData.pointers[currentPointerIndex].id = id;
3844 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3845 current->rawPointerData.markIdBit(id,
3846 current->rawPointerData.isHovering(
3847 currentPointerIndex));
3848 usedIdBits.markBit(id);
3849
3850#if DEBUG_POINTER_ASSIGNMENT
3851 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3852 ", distance=%" PRIu64,
3853 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3854#endif
3855 break;
3856 }
3857 }
3858
3859 // Assign fresh ids to pointers that were not matched in the process.
3860 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3861 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3862 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3863
3864 current->rawPointerData.pointers[currentPointerIndex].id = id;
3865 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3866 current->rawPointerData.markIdBit(id,
3867 current->rawPointerData.isHovering(currentPointerIndex));
3868
3869#if DEBUG_POINTER_ASSIGNMENT
3870 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3871#endif
3872 }
3873}
3874
3875int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3876 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3877 return AKEY_STATE_VIRTUAL;
3878 }
3879
3880 for (const VirtualKey& virtualKey : mVirtualKeys) {
3881 if (virtualKey.keyCode == keyCode) {
3882 return AKEY_STATE_UP;
3883 }
3884 }
3885
3886 return AKEY_STATE_UNKNOWN;
3887}
3888
3889int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3890 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3891 return AKEY_STATE_VIRTUAL;
3892 }
3893
3894 for (const VirtualKey& virtualKey : mVirtualKeys) {
3895 if (virtualKey.scanCode == scanCode) {
3896 return AKEY_STATE_UP;
3897 }
3898 }
3899
3900 return AKEY_STATE_UNKNOWN;
3901}
3902
3903bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3904 const int32_t* keyCodes, uint8_t* outFlags) {
3905 for (const VirtualKey& virtualKey : mVirtualKeys) {
3906 for (size_t i = 0; i < numCodes; i++) {
3907 if (virtualKey.keyCode == keyCodes[i]) {
3908 outFlags[i] = 1;
3909 }
3910 }
3911 }
3912
3913 return true;
3914}
3915
3916std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3917 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003918 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003919 return std::make_optional(mPointerController->getDisplayId());
3920 } else {
3921 return std::make_optional(mViewport.displayId);
3922 }
3923 }
3924 return std::nullopt;
3925}
3926
3927} // namespace android