blob: b748bfeffeb7615a6eb842ee556e16e00f7daa05 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
Chris Yea03dd232020-09-08 19:21:09 -070021#include <input/NamedEnum.h>
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070022#include "TouchInputMapper.h"
23
24#include "CursorButtonAccumulator.h"
25#include "CursorScrollAccumulator.h"
26#include "TouchButtonAccumulator.h"
27#include "TouchCursorInputMapperCommon.h"
28
29namespace android {
30
31// --- Constants ---
32
33// Maximum amount of latency to add to touch events while waiting for data from an
34// external stylus.
35static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
36
37// Maximum amount of time to wait on touch data before pushing out new pressure data.
38static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
39
40// Artificial latency on synthetic events created from stylus data without corresponding touch
41// data.
42static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
43
44// --- Static Definitions ---
45
46template <typename T>
47inline static void swap(T& a, T& b) {
48 T temp = a;
49 a = b;
50 b = temp;
51}
52
53static float calculateCommonVector(float a, float b) {
54 if (a > 0 && b > 0) {
55 return a < b ? a : b;
56 } else if (a < 0 && b < 0) {
57 return a > b ? a : b;
58 } else {
59 return 0;
60 }
61}
62
63inline static float distance(float x1, float y1, float x2, float y2) {
64 return hypotf(x1 - x2, y1 - y2);
65}
66
67inline static int32_t signExtendNybble(int32_t value) {
68 return value >= 8 ? value - 16 : value;
69}
70
71// --- RawPointerAxes ---
72
73RawPointerAxes::RawPointerAxes() {
74 clear();
75}
76
77void RawPointerAxes::clear() {
78 x.clear();
79 y.clear();
80 pressure.clear();
81 touchMajor.clear();
82 touchMinor.clear();
83 toolMajor.clear();
84 toolMinor.clear();
85 orientation.clear();
86 distance.clear();
87 tiltX.clear();
88 tiltY.clear();
89 trackingId.clear();
90 slot.clear();
91}
92
93// --- RawPointerData ---
94
95RawPointerData::RawPointerData() {
96 clear();
97}
98
99void RawPointerData::clear() {
100 pointerCount = 0;
101 clearIdBits();
102}
103
104void RawPointerData::copyFrom(const RawPointerData& other) {
105 pointerCount = other.pointerCount;
106 hoveringIdBits = other.hoveringIdBits;
107 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800108 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109
110 for (uint32_t i = 0; i < pointerCount; i++) {
111 pointers[i] = other.pointers[i];
112
113 int id = pointers[i].id;
114 idToIndex[id] = other.idToIndex[id];
115 }
116}
117
118void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
119 float x = 0, y = 0;
120 uint32_t count = touchingIdBits.count();
121 if (count) {
122 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
123 uint32_t id = idBits.clearFirstMarkedBit();
124 const Pointer& pointer = pointerForId(id);
125 x += pointer.x;
126 y += pointer.y;
127 }
128 x /= count;
129 y /= count;
130 }
131 *outX = x;
132 *outY = y;
133}
134
135// --- CookedPointerData ---
136
137CookedPointerData::CookedPointerData() {
138 clear();
139}
140
141void CookedPointerData::clear() {
142 pointerCount = 0;
143 hoveringIdBits.clear();
144 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800145 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000146 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700147}
148
149void CookedPointerData::copyFrom(const CookedPointerData& other) {
150 pointerCount = other.pointerCount;
151 hoveringIdBits = other.hoveringIdBits;
152 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000153 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700154
155 for (uint32_t i = 0; i < pointerCount; i++) {
156 pointerProperties[i].copyFrom(other.pointerProperties[i]);
157 pointerCoords[i].copyFrom(other.pointerCoords[i]);
158
159 int id = pointerProperties[i].id;
160 idToIndex[id] = other.idToIndex[id];
161 }
162}
163
164// --- TouchInputMapper ---
165
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800166TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
167 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700168 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100169 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800170 mRawSurfaceWidth(-1),
171 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700172 mSurfaceLeft(0),
173 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700174 mSurfaceRight(0),
175 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700176 mPhysicalWidth(-1),
177 mPhysicalHeight(-1),
178 mPhysicalLeft(0),
179 mPhysicalTop(0),
180 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
181
182TouchInputMapper::~TouchInputMapper() {}
183
184uint32_t TouchInputMapper::getSources() {
185 return mSource;
186}
187
188void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
189 InputMapper::populateDeviceInfo(info);
190
Michael Wright227c5542020-07-02 18:30:52 +0100191 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 info->addMotionRange(mOrientedRanges.x);
193 info->addMotionRange(mOrientedRanges.y);
194 info->addMotionRange(mOrientedRanges.pressure);
195
Chris Yef74dc422020-09-02 22:41:50 -0700196 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700197 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
198 //
199 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
200 // motion, i.e. the hardware dimensions, as the finger could move completely across the
201 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700202 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
203 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
204 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
205 x.fuzz, x.resolution);
206 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
207 y.fuzz, y.resolution);
208 }
209
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700210 if (mOrientedRanges.haveSize) {
211 info->addMotionRange(mOrientedRanges.size);
212 }
213
214 if (mOrientedRanges.haveTouchSize) {
215 info->addMotionRange(mOrientedRanges.touchMajor);
216 info->addMotionRange(mOrientedRanges.touchMinor);
217 }
218
219 if (mOrientedRanges.haveToolSize) {
220 info->addMotionRange(mOrientedRanges.toolMajor);
221 info->addMotionRange(mOrientedRanges.toolMinor);
222 }
223
224 if (mOrientedRanges.haveOrientation) {
225 info->addMotionRange(mOrientedRanges.orientation);
226 }
227
228 if (mOrientedRanges.haveDistance) {
229 info->addMotionRange(mOrientedRanges.distance);
230 }
231
232 if (mOrientedRanges.haveTilt) {
233 info->addMotionRange(mOrientedRanges.tilt);
234 }
235
236 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
237 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
238 0.0f);
239 }
240 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
241 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
242 0.0f);
243 }
Michael Wright227c5542020-07-02 18:30:52 +0100244 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700245 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
246 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
247 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
248 x.fuzz, x.resolution);
249 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
250 y.fuzz, y.resolution);
251 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
252 x.fuzz, x.resolution);
253 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
254 y.fuzz, y.resolution);
255 }
256 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
257 }
258}
259
260void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700261 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
262 NamedEnum::string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700263 dumpParameters(dump);
264 dumpVirtualKeys(dump);
265 dumpRawPointerAxes(dump);
266 dumpCalibration(dump);
267 dumpAffineTransformation(dump);
268 dumpSurface(dump);
269
270 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
271 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
272 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
273 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
274 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
275 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
276 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
277 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
278 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
279 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
280 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
281 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
282 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
283 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
284 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
285 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
286 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
287
288 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
289 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
290 mLastRawState.rawPointerData.pointerCount);
291 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
292 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
293 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
294 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
295 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
296 "toolType=%d, isHovering=%s\n",
297 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
298 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
299 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
300 pointer.distance, pointer.toolType, toString(pointer.isHovering));
301 }
302
303 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
304 mLastCookedState.buttonState);
305 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
306 mLastCookedState.cookedPointerData.pointerCount);
307 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
308 const PointerProperties& pointerProperties =
309 mLastCookedState.cookedPointerData.pointerProperties[i];
310 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000311 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
312 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
313 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
315 "toolType=%d, isHovering=%s\n",
316 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
327 pointerProperties.toolType,
328 toString(mLastCookedState.cookedPointerData.isHovering(i)));
329 }
330
331 dump += INDENT3 "Stylus Fusion:\n";
332 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
333 toString(mExternalStylusConnected));
334 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
335 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
336 mExternalStylusFusionTimeout);
337 dump += INDENT3 "External Stylus State:\n";
338 dumpStylusState(dump, mExternalStylusState);
339
Michael Wright227c5542020-07-02 18:30:52 +0100340 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
342 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
343 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
344 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
345 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
346 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
347 }
348}
349
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
351 uint32_t changes) {
352 InputMapper::configure(when, config, changes);
353
354 mConfig = *config;
355
356 if (!changes) { // first time only
357 // Configure basic parameters.
358 configureParameters();
359
360 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mCursorScrollAccumulator.configure(getDeviceContext());
362 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700363
364 // Configure absolute axis information.
365 configureRawPointerAxes();
366
367 // Prepare input device calibration.
368 parseCalibration();
369 resolveCalibration();
370 }
371
372 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
373 // Update location calibration to reflect current settings
374 updateAffineTransformation();
375 }
376
377 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
378 // Update pointer speed.
379 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
380 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
381 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 }
383
384 bool resetNeeded = false;
385 if (!changes ||
386 (changes &
387 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800388 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
390 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
391 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
392 // Configure device sources, surface dimensions, orientation and
393 // scaling factors.
394 configureSurface(when, &resetNeeded);
395 }
396
397 if (changes && resetNeeded) {
398 // Send reset, unless this is the first time the device has been configured,
399 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -0600400 getContext()->notifyDeviceReset(when, getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700401 }
402}
403
404void TouchInputMapper::resolveExternalStylusPresence() {
405 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800406 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700407 mExternalStylusConnected = !devices.empty();
408
409 if (!mExternalStylusConnected) {
410 resetExternalStylus();
411 }
412}
413
414void TouchInputMapper::configureParameters() {
415 // Use the pointer presentation mode for devices that do not support distinct
416 // multitouch. The spot-based presentation relies on being able to accurately
417 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100419 ? Parameters::GestureMode::SINGLE_TOUCH
420 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421
422 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800423 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
424 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700425 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100426 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700427 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100428 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700429 } else if (gestureModeString != "default") {
430 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
431 }
432 }
433
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800434 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700435 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100436 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800437 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100439 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800440 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
441 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700442 // The device is a cursor device with a touch pad attached.
443 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100444 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700445 } else {
446 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100447 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448 }
449
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800450 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700451
452 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800453 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
454 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100456 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100458 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100460 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700461 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100462 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463 } else if (deviceTypeString != "default") {
464 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
465 }
466 }
467
Michael Wright227c5542020-07-02 18:30:52 +0100468 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800469 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
470 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700471
472 mParameters.hasAssociatedDisplay = false;
473 mParameters.associatedDisplayIsExternal = false;
474 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100475 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
476 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700477 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100478 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800479 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700480 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800481 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
482 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700483 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
484 }
485 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800486 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700487 mParameters.hasAssociatedDisplay = true;
488 }
489
490 // Initial downs on external touch devices should wake the device.
491 // Normally we don't do this for internal touch screens to prevent them from waking
492 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800493 mParameters.wake = getDeviceContext().isExternal();
494 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700495}
496
497void TouchInputMapper::dumpParameters(std::string& dump) {
498 dump += INDENT3 "Parameters:\n";
499
Chris Yea03dd232020-09-08 19:21:09 -0700500 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700501
Chris Yea03dd232020-09-08 19:21:09 -0700502 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700503
504 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
505 "displayId='%s'\n",
506 toString(mParameters.hasAssociatedDisplay),
507 toString(mParameters.associatedDisplayIsExternal),
508 mParameters.uniqueDisplayId.c_str());
509 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
510}
511
512void TouchInputMapper::configureRawPointerAxes() {
513 mRawPointerAxes.clear();
514}
515
516void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
517 dump += INDENT3 "Raw Touch Axes:\n";
518 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
531}
532
533bool TouchInputMapper::hasExternalStylus() const {
534 return mExternalStylusConnected;
535}
536
537/**
538 * Determine which DisplayViewport to use.
539 * 1. If display port is specified, return the matching viewport. If matching viewport not
540 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800541 * 2. Always use the suggested viewport from WindowManagerService for pointers.
542 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700543 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800544 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700545 */
546std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800547 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800548 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700549 if (displayPort) {
550 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800551 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700552 }
553
Michael Wright227c5542020-07-02 18:30:52 +0100554 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800555 std::optional<DisplayViewport> viewport =
556 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
557 if (viewport) {
558 return viewport;
559 } else {
560 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
561 mConfig.defaultPointerDisplayId);
562 }
563 }
564
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700565 // Check if uniqueDisplayId is specified in idc file.
566 if (!mParameters.uniqueDisplayId.empty()) {
567 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
568 }
569
570 ViewportType viewportTypeToUse;
571 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100572 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700573 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100574 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700575 }
576
577 std::optional<DisplayViewport> viewport =
578 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100579 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700580 ALOGW("Input device %s should be associated with external display, "
581 "fallback to internal one for the external viewport is not found.",
582 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100583 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700584 }
585
586 return viewport;
587 }
588
589 // No associated display, return a non-display viewport.
590 DisplayViewport newViewport;
591 // Raw width and height in the natural orientation.
592 int32_t rawWidth = mRawPointerAxes.getRawWidth();
593 int32_t rawHeight = mRawPointerAxes.getRawHeight();
594 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
595 return std::make_optional(newViewport);
596}
597
598void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100599 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700600
601 resolveExternalStylusPresence();
602
603 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100604 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800605 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700606 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100607 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700608 if (hasStylus()) {
609 mSource |= AINPUT_SOURCE_STYLUS;
610 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800611 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700612 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100613 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700614 if (hasStylus()) {
615 mSource |= AINPUT_SOURCE_STYLUS;
616 }
617 if (hasExternalStylus()) {
618 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
619 }
Michael Wright227c5542020-07-02 18:30:52 +0100620 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700621 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100622 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700623 } else {
624 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100625 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700626 }
627
628 // Ensure we have valid X and Y axes.
629 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
630 ALOGW("Touch device '%s' did not report support for X or Y axis! "
631 "The device will be inoperable.",
632 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100633 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700634 return;
635 }
636
637 // Get associated display dimensions.
638 std::optional<DisplayViewport> newViewport = findViewport();
639 if (!newViewport) {
640 ALOGI("Touch device '%s' could not query the properties of its associated "
641 "display. The device will be inoperable until the display size "
642 "becomes available.",
643 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100644 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700645 return;
646 }
647
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000648 if (!newViewport->isActive) {
649 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
650 getDeviceName().c_str(), getDeviceId());
651 mDeviceMode = DeviceMode::DISABLED;
652 return;
653 }
654
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700655 // Raw width and height in the natural orientation.
656 int32_t rawWidth = mRawPointerAxes.getRawWidth();
657 int32_t rawHeight = mRawPointerAxes.getRawHeight();
658
659 bool viewportChanged = mViewport != *newViewport;
660 if (viewportChanged) {
661 mViewport = *newViewport;
662
Michael Wright227c5542020-07-02 18:30:52 +0100663 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700664 // Convert rotated viewport to natural surface coordinates.
665 int32_t naturalLogicalWidth, naturalLogicalHeight;
666 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
667 int32_t naturalPhysicalLeft, naturalPhysicalTop;
668 int32_t naturalDeviceWidth, naturalDeviceHeight;
669 switch (mViewport.orientation) {
670 case DISPLAY_ORIENTATION_90:
671 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
672 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
673 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
674 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800675 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700676 naturalPhysicalTop = mViewport.physicalLeft;
677 naturalDeviceWidth = mViewport.deviceHeight;
678 naturalDeviceHeight = mViewport.deviceWidth;
679 break;
680 case DISPLAY_ORIENTATION_180:
681 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
682 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
683 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
684 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
685 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
686 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
687 naturalDeviceWidth = mViewport.deviceWidth;
688 naturalDeviceHeight = mViewport.deviceHeight;
689 break;
690 case DISPLAY_ORIENTATION_270:
691 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
692 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
693 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
694 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
695 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800696 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700697 naturalDeviceWidth = mViewport.deviceHeight;
698 naturalDeviceHeight = mViewport.deviceWidth;
699 break;
700 case DISPLAY_ORIENTATION_0:
701 default:
702 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
703 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
704 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
705 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
706 naturalPhysicalLeft = mViewport.physicalLeft;
707 naturalPhysicalTop = mViewport.physicalTop;
708 naturalDeviceWidth = mViewport.deviceWidth;
709 naturalDeviceHeight = mViewport.deviceHeight;
710 break;
711 }
712
713 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
714 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
715 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
716 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
717 }
718
719 mPhysicalWidth = naturalPhysicalWidth;
720 mPhysicalHeight = naturalPhysicalHeight;
721 mPhysicalLeft = naturalPhysicalLeft;
722 mPhysicalTop = naturalPhysicalTop;
723
Arthur Hung4197f6b2020-03-16 15:39:59 +0800724 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
725 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700726 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
727 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800728 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
729 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700730
731 mSurfaceOrientation =
732 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
733 } else {
734 mPhysicalWidth = rawWidth;
735 mPhysicalHeight = rawHeight;
736 mPhysicalLeft = 0;
737 mPhysicalTop = 0;
738
Arthur Hung4197f6b2020-03-16 15:39:59 +0800739 mRawSurfaceWidth = rawWidth;
740 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700741 mSurfaceLeft = 0;
742 mSurfaceTop = 0;
743 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
744 }
745 }
746
747 // If moving between pointer modes, need to reset some state.
748 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
749 if (deviceModeChanged) {
750 mOrientedRanges.clear();
751 }
752
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800753 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
754 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100755 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800756 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
757 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800758 if (mPointerController == nullptr) {
759 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700760 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800761 if (mConfig.pointerCapture) {
762 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
763 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700764 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100765 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700766 }
767
768 if (viewportChanged || deviceModeChanged) {
769 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
770 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800771 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700772 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
773
774 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800775 mXScale = float(mRawSurfaceWidth) / rawWidth;
776 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700777 mXTranslate = -mSurfaceLeft;
778 mYTranslate = -mSurfaceTop;
779 mXPrecision = 1.0f / mXScale;
780 mYPrecision = 1.0f / mYScale;
781
782 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
783 mOrientedRanges.x.source = mSource;
784 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
785 mOrientedRanges.y.source = mSource;
786
787 configureVirtualKeys();
788
789 // Scale factor for terms that are not oriented in a particular axis.
790 // If the pixels are square then xScale == yScale otherwise we fake it
791 // by choosing an average.
792 mGeometricScale = avg(mXScale, mYScale);
793
794 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800795 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700796
797 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100798 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700799 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
800 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
801 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
802 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
803 } else {
804 mSizeScale = 0.0f;
805 }
806
807 mOrientedRanges.haveTouchSize = true;
808 mOrientedRanges.haveToolSize = true;
809 mOrientedRanges.haveSize = true;
810
811 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
812 mOrientedRanges.touchMajor.source = mSource;
813 mOrientedRanges.touchMajor.min = 0;
814 mOrientedRanges.touchMajor.max = diagonalSize;
815 mOrientedRanges.touchMajor.flat = 0;
816 mOrientedRanges.touchMajor.fuzz = 0;
817 mOrientedRanges.touchMajor.resolution = 0;
818
819 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
820 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
821
822 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
823 mOrientedRanges.toolMajor.source = mSource;
824 mOrientedRanges.toolMajor.min = 0;
825 mOrientedRanges.toolMajor.max = diagonalSize;
826 mOrientedRanges.toolMajor.flat = 0;
827 mOrientedRanges.toolMajor.fuzz = 0;
828 mOrientedRanges.toolMajor.resolution = 0;
829
830 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
831 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
832
833 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
834 mOrientedRanges.size.source = mSource;
835 mOrientedRanges.size.min = 0;
836 mOrientedRanges.size.max = 1.0;
837 mOrientedRanges.size.flat = 0;
838 mOrientedRanges.size.fuzz = 0;
839 mOrientedRanges.size.resolution = 0;
840 } else {
841 mSizeScale = 0.0f;
842 }
843
844 // Pressure factors.
845 mPressureScale = 0;
846 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100847 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
848 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700849 if (mCalibration.havePressureScale) {
850 mPressureScale = mCalibration.pressureScale;
851 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
852 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
853 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
854 }
855 }
856
857 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
858 mOrientedRanges.pressure.source = mSource;
859 mOrientedRanges.pressure.min = 0;
860 mOrientedRanges.pressure.max = pressureMax;
861 mOrientedRanges.pressure.flat = 0;
862 mOrientedRanges.pressure.fuzz = 0;
863 mOrientedRanges.pressure.resolution = 0;
864
865 // Tilt
866 mTiltXCenter = 0;
867 mTiltXScale = 0;
868 mTiltYCenter = 0;
869 mTiltYScale = 0;
870 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
871 if (mHaveTilt) {
872 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
873 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
874 mTiltXScale = M_PI / 180;
875 mTiltYScale = M_PI / 180;
876
877 mOrientedRanges.haveTilt = true;
878
879 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
880 mOrientedRanges.tilt.source = mSource;
881 mOrientedRanges.tilt.min = 0;
882 mOrientedRanges.tilt.max = M_PI_2;
883 mOrientedRanges.tilt.flat = 0;
884 mOrientedRanges.tilt.fuzz = 0;
885 mOrientedRanges.tilt.resolution = 0;
886 }
887
888 // Orientation
889 mOrientationScale = 0;
890 if (mHaveTilt) {
891 mOrientedRanges.haveOrientation = true;
892
893 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
894 mOrientedRanges.orientation.source = mSource;
895 mOrientedRanges.orientation.min = -M_PI;
896 mOrientedRanges.orientation.max = M_PI;
897 mOrientedRanges.orientation.flat = 0;
898 mOrientedRanges.orientation.fuzz = 0;
899 mOrientedRanges.orientation.resolution = 0;
900 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100901 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100903 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 if (mRawPointerAxes.orientation.valid) {
905 if (mRawPointerAxes.orientation.maxValue > 0) {
906 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
907 } else if (mRawPointerAxes.orientation.minValue < 0) {
908 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
909 } else {
910 mOrientationScale = 0;
911 }
912 }
913 }
914
915 mOrientedRanges.haveOrientation = true;
916
917 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
918 mOrientedRanges.orientation.source = mSource;
919 mOrientedRanges.orientation.min = -M_PI_2;
920 mOrientedRanges.orientation.max = M_PI_2;
921 mOrientedRanges.orientation.flat = 0;
922 mOrientedRanges.orientation.fuzz = 0;
923 mOrientedRanges.orientation.resolution = 0;
924 }
925
926 // Distance
927 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100928 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
929 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700930 if (mCalibration.haveDistanceScale) {
931 mDistanceScale = mCalibration.distanceScale;
932 } else {
933 mDistanceScale = 1.0f;
934 }
935 }
936
937 mOrientedRanges.haveDistance = true;
938
939 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
940 mOrientedRanges.distance.source = mSource;
941 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
942 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
943 mOrientedRanges.distance.flat = 0;
944 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
945 mOrientedRanges.distance.resolution = 0;
946 }
947
948 // Compute oriented precision, scales and ranges.
949 // Note that the maximum value reported is an inclusive maximum value so it is one
950 // unit less than the total width or height of surface.
951 switch (mSurfaceOrientation) {
952 case DISPLAY_ORIENTATION_90:
953 case DISPLAY_ORIENTATION_270:
954 mOrientedXPrecision = mYPrecision;
955 mOrientedYPrecision = mXPrecision;
956
957 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800958 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700959 mOrientedRanges.x.flat = 0;
960 mOrientedRanges.x.fuzz = 0;
961 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
962
963 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800964 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700965 mOrientedRanges.y.flat = 0;
966 mOrientedRanges.y.fuzz = 0;
967 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
968 break;
969
970 default:
971 mOrientedXPrecision = mXPrecision;
972 mOrientedYPrecision = mYPrecision;
973
974 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800975 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700976 mOrientedRanges.x.flat = 0;
977 mOrientedRanges.x.fuzz = 0;
978 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
979
980 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800981 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700982 mOrientedRanges.y.flat = 0;
983 mOrientedRanges.y.fuzz = 0;
984 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
985 break;
986 }
987
988 // Location
989 updateAffineTransformation();
990
Michael Wright227c5542020-07-02 18:30:52 +0100991 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700992 // Compute pointer gesture detection parameters.
993 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +0800994 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700995
996 // Scale movements such that one whole swipe of the touch pad covers a
997 // given area relative to the diagonal size of the display when no acceleration
998 // is applied.
999 // Assume that the touch pad has a square aspect ratio such that movements in
1000 // X and Y of the same number of raw units cover the same physical distance.
1001 mPointerXMovementScale =
1002 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1003 mPointerYMovementScale = mPointerXMovementScale;
1004
1005 // Scale zooms to cover a smaller range of the display than movements do.
1006 // This value determines the area around the pointer that is affected by freeform
1007 // pointer gestures.
1008 mPointerXZoomScale =
1009 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1010 mPointerYZoomScale = mPointerXZoomScale;
1011
1012 // Max width between pointers to detect a swipe gesture is more than some fraction
1013 // of the diagonal axis of the touch pad. Touches that are wider than this are
1014 // translated into freeform gestures.
1015 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1016
1017 // Abort current pointer usages because the state has changed.
1018 abortPointerUsage(when, 0 /*policyFlags*/);
1019 }
1020
1021 // Inform the dispatcher about the changes.
1022 *outResetNeeded = true;
1023 bumpGeneration();
1024 }
1025}
1026
1027void TouchInputMapper::dumpSurface(std::string& dump) {
1028 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001029 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1030 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001031 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1032 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001033 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1034 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1036 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1037 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1038 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1039 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1040}
1041
1042void TouchInputMapper::configureVirtualKeys() {
1043 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001044 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001045
1046 mVirtualKeys.clear();
1047
1048 if (virtualKeyDefinitions.size() == 0) {
1049 return;
1050 }
1051
1052 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1053 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1054 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1055 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1056
1057 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1058 VirtualKey virtualKey;
1059
1060 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1061 int32_t keyCode;
1062 int32_t dummyKeyMetaState;
1063 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001064 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1065 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1067 continue; // drop the key
1068 }
1069
1070 virtualKey.keyCode = keyCode;
1071 virtualKey.flags = flags;
1072
1073 // convert the key definition's display coordinates into touch coordinates for a hit box
1074 int32_t halfWidth = virtualKeyDefinition.width / 2;
1075 int32_t halfHeight = virtualKeyDefinition.height / 2;
1076
1077 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001078 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001079 touchScreenLeft;
1080 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001081 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001083 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1084 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001085 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001086 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1087 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001088 touchScreenTop;
1089 mVirtualKeys.push_back(virtualKey);
1090 }
1091}
1092
1093void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1094 if (!mVirtualKeys.empty()) {
1095 dump += INDENT3 "Virtual Keys:\n";
1096
1097 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1098 const VirtualKey& virtualKey = mVirtualKeys[i];
1099 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1100 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1101 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1102 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1103 }
1104 }
1105}
1106
1107void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001108 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 Calibration& out = mCalibration;
1110
1111 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001112 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 String8 sizeCalibrationString;
1114 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1115 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001116 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001118 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001119 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001120 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001121 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001122 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001124 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001125 } else if (sizeCalibrationString != "default") {
1126 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1127 }
1128 }
1129
1130 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1131 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1132 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1133
1134 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001135 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 String8 pressureCalibrationString;
1137 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1138 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001139 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001140 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001141 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (pressureCalibrationString != "default") {
1145 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1146 pressureCalibrationString.string());
1147 }
1148 }
1149
1150 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1151
1152 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001153 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 String8 orientationCalibrationString;
1155 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1156 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001157 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001158 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001159 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001161 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001162 } else if (orientationCalibrationString != "default") {
1163 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1164 orientationCalibrationString.string());
1165 }
1166 }
1167
1168 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 String8 distanceCalibrationString;
1171 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1172 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (distanceCalibrationString != "default") {
1177 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1178 distanceCalibrationString.string());
1179 }
1180 }
1181
1182 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1183
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001185 String8 coverageCalibrationString;
1186 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1187 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (coverageCalibrationString != "default") {
1192 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1193 coverageCalibrationString.string());
1194 }
1195 }
1196}
1197
1198void TouchInputMapper::resolveCalibration() {
1199 // Size
1200 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001201 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1202 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 }
1204 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001205 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001206 }
1207
1208 // Pressure
1209 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001210 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1211 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 }
1213 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001214 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 }
1216
1217 // Orientation
1218 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001219 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1220 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 }
1222 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001223 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 }
1225
1226 // Distance
1227 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001228 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1229 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 }
1231 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001232 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 }
1234
1235 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001236 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1237 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 }
1239}
1240
1241void TouchInputMapper::dumpCalibration(std::string& dump) {
1242 dump += INDENT3 "Calibration:\n";
1243
1244 // Size
1245 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001246 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 dump += INDENT4 "touch.size.calibration: none\n";
1248 break;
Michael Wright227c5542020-07-02 18:30:52 +01001249 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 dump += INDENT4 "touch.size.calibration: geometric\n";
1251 break;
Michael Wright227c5542020-07-02 18:30:52 +01001252 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 dump += INDENT4 "touch.size.calibration: diameter\n";
1254 break;
Michael Wright227c5542020-07-02 18:30:52 +01001255 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256 dump += INDENT4 "touch.size.calibration: box\n";
1257 break;
Michael Wright227c5542020-07-02 18:30:52 +01001258 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 dump += INDENT4 "touch.size.calibration: area\n";
1260 break;
1261 default:
1262 ALOG_ASSERT(false);
1263 }
1264
1265 if (mCalibration.haveSizeScale) {
1266 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1267 }
1268
1269 if (mCalibration.haveSizeBias) {
1270 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1271 }
1272
1273 if (mCalibration.haveSizeIsSummed) {
1274 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1275 toString(mCalibration.sizeIsSummed));
1276 }
1277
1278 // Pressure
1279 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001280 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 dump += INDENT4 "touch.pressure.calibration: none\n";
1282 break;
Michael Wright227c5542020-07-02 18:30:52 +01001283 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 dump += INDENT4 "touch.pressure.calibration: physical\n";
1285 break;
Michael Wright227c5542020-07-02 18:30:52 +01001286 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1288 break;
1289 default:
1290 ALOG_ASSERT(false);
1291 }
1292
1293 if (mCalibration.havePressureScale) {
1294 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1295 }
1296
1297 // Orientation
1298 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001299 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 dump += INDENT4 "touch.orientation.calibration: none\n";
1301 break;
Michael Wright227c5542020-07-02 18:30:52 +01001302 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1304 break;
Michael Wright227c5542020-07-02 18:30:52 +01001305 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 dump += INDENT4 "touch.orientation.calibration: vector\n";
1307 break;
1308 default:
1309 ALOG_ASSERT(false);
1310 }
1311
1312 // Distance
1313 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001314 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.distance.calibration: none\n";
1316 break;
Michael Wright227c5542020-07-02 18:30:52 +01001317 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.distance.calibration: scaled\n";
1319 break;
1320 default:
1321 ALOG_ASSERT(false);
1322 }
1323
1324 if (mCalibration.haveDistanceScale) {
1325 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1326 }
1327
1328 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.coverage.calibration: none\n";
1331 break;
Michael Wright227c5542020-07-02 18:30:52 +01001332 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333 dump += INDENT4 "touch.coverage.calibration: box\n";
1334 break;
1335 default:
1336 ALOG_ASSERT(false);
1337 }
1338}
1339
1340void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1341 dump += INDENT3 "Affine Transformation:\n";
1342
1343 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1344 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1345 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1346 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1347 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1348 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1349}
1350
1351void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001352 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 mSurfaceOrientation);
1354}
1355
1356void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001357 mCursorButtonAccumulator.reset(getDeviceContext());
1358 mCursorScrollAccumulator.reset(getDeviceContext());
1359 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360
1361 mPointerVelocityControl.reset();
1362 mWheelXVelocityControl.reset();
1363 mWheelYVelocityControl.reset();
1364
1365 mRawStatesPending.clear();
1366 mCurrentRawState.clear();
1367 mCurrentCookedState.clear();
1368 mLastRawState.clear();
1369 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001370 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001371 mSentHoverEnter = false;
1372 mHavePointerIds = false;
1373 mCurrentMotionAborted = false;
1374 mDownTime = 0;
1375
1376 mCurrentVirtualKey.down = false;
1377
1378 mPointerGesture.reset();
1379 mPointerSimple.reset();
1380 resetExternalStylus();
1381
1382 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001383 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001384 mPointerController->clearSpots();
1385 }
1386
1387 InputMapper::reset(when);
1388}
1389
1390void TouchInputMapper::resetExternalStylus() {
1391 mExternalStylusState.clear();
1392 mExternalStylusId = -1;
1393 mExternalStylusFusionTimeout = LLONG_MAX;
1394 mExternalStylusDataPending = false;
1395}
1396
1397void TouchInputMapper::clearStylusDataPendingFlags() {
1398 mExternalStylusDataPending = false;
1399 mExternalStylusFusionTimeout = LLONG_MAX;
1400}
1401
1402void TouchInputMapper::process(const RawEvent* rawEvent) {
1403 mCursorButtonAccumulator.process(rawEvent);
1404 mCursorScrollAccumulator.process(rawEvent);
1405 mTouchButtonAccumulator.process(rawEvent);
1406
1407 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1408 sync(rawEvent->when);
1409 }
1410}
1411
1412void TouchInputMapper::sync(nsecs_t when) {
1413 const RawState* last =
1414 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1415
1416 // Push a new state.
1417 mRawStatesPending.emplace_back();
1418
1419 RawState* next = &mRawStatesPending.back();
1420 next->clear();
1421 next->when = when;
1422
1423 // Sync button state.
1424 next->buttonState =
1425 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1426
1427 // Sync scroll
1428 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1429 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1430 mCursorScrollAccumulator.finishSync();
1431
1432 // Sync touch
1433 syncTouch(when, next);
1434
1435 // Assign pointer ids.
1436 if (!mHavePointerIds) {
1437 assignPointerIds(last, next);
1438 }
1439
1440#if DEBUG_RAW_EVENTS
1441 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001442 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001443 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1444 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001445 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1446 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447#endif
1448
1449 processRawTouches(false /*timeout*/);
1450}
1451
1452void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001453 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001454 // Drop all input if the device is disabled.
Garfield Tanc734e4f2021-01-15 20:01:39 -08001455 cancelTouch(mCurrentRawState.when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456 mCurrentRawState.clear();
1457 mRawStatesPending.clear();
Garfield Tanc734e4f2021-01-15 20:01:39 -08001458 mCurrentCookedState.clear();
1459 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001460 return;
1461 }
1462
1463 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1464 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1465 // touching the current state will only observe the events that have been dispatched to the
1466 // rest of the pipeline.
1467 const size_t N = mRawStatesPending.size();
1468 size_t count;
1469 for (count = 0; count < N; count++) {
1470 const RawState& next = mRawStatesPending[count];
1471
1472 // A failure to assign the stylus id means that we're waiting on stylus data
1473 // and so should defer the rest of the pipeline.
1474 if (assignExternalStylusId(next, timeout)) {
1475 break;
1476 }
1477
1478 // All ready to go.
1479 clearStylusDataPendingFlags();
1480 mCurrentRawState.copyFrom(next);
1481 if (mCurrentRawState.when < mLastRawState.when) {
1482 mCurrentRawState.when = mLastRawState.when;
1483 }
1484 cookAndDispatch(mCurrentRawState.when);
1485 }
1486 if (count != 0) {
1487 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1488 }
1489
1490 if (mExternalStylusDataPending) {
1491 if (timeout) {
1492 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1493 clearStylusDataPendingFlags();
1494 mCurrentRawState.copyFrom(mLastRawState);
1495#if DEBUG_STYLUS_FUSION
1496 ALOGD("Timeout expired, synthesizing event with new stylus data");
1497#endif
1498 cookAndDispatch(when);
1499 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1500 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1501 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1502 }
1503 }
1504}
1505
1506void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1507 // Always start with a clean state.
1508 mCurrentCookedState.clear();
1509
1510 // Apply stylus buttons to current raw state.
1511 applyExternalStylusButtonState(when);
1512
1513 // Handle policy on initial down or hover events.
1514 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1515 mCurrentRawState.rawPointerData.pointerCount != 0;
1516
1517 uint32_t policyFlags = 0;
1518 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1519 if (initialDown || buttonsPressed) {
1520 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001521 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 getContext()->fadePointer();
1523 }
1524
1525 if (mParameters.wake) {
1526 policyFlags |= POLICY_FLAG_WAKE;
1527 }
1528 }
1529
1530 // Consume raw off-screen touches before cooking pointer data.
1531 // If touches are consumed, subsequent code will not receive any pointer data.
1532 if (consumeRawTouches(when, policyFlags)) {
1533 mCurrentRawState.rawPointerData.clear();
1534 }
1535
1536 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1537 // with cooked pointer data that has the same ids and indices as the raw data.
1538 // The following code can use either the raw or cooked data, as needed.
1539 cookPointerData();
1540
1541 // Apply stylus pressure to current cooked state.
1542 applyExternalStylusTouchState(when);
1543
1544 // Synthesize key down from raw buttons if needed.
1545 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1546 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1547 mCurrentCookedState.buttonState);
1548
1549 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001550 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001551 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1552 uint32_t id = idBits.clearFirstMarkedBit();
1553 const RawPointerData::Pointer& pointer =
1554 mCurrentRawState.rawPointerData.pointerForId(id);
1555 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1556 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1557 mCurrentCookedState.stylusIdBits.markBit(id);
1558 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1559 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1560 mCurrentCookedState.fingerIdBits.markBit(id);
1561 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1562 mCurrentCookedState.mouseIdBits.markBit(id);
1563 }
1564 }
1565 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1566 uint32_t id = idBits.clearFirstMarkedBit();
1567 const RawPointerData::Pointer& pointer =
1568 mCurrentRawState.rawPointerData.pointerForId(id);
1569 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1570 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1571 mCurrentCookedState.stylusIdBits.markBit(id);
1572 }
1573 }
1574
1575 // Stylus takes precedence over all tools, then mouse, then finger.
1576 PointerUsage pointerUsage = mPointerUsage;
1577 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1578 mCurrentCookedState.mouseIdBits.clear();
1579 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001580 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001581 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1582 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001583 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001584 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1585 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001586 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001587 }
1588
1589 dispatchPointerUsage(when, policyFlags, pointerUsage);
1590 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001591 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592
1593 if (!mCurrentMotionAborted) {
1594 dispatchButtonRelease(when, policyFlags);
1595 dispatchHoverExit(when, policyFlags);
1596 dispatchTouches(when, policyFlags);
1597 dispatchHoverEnterAndMove(when, policyFlags);
1598 dispatchButtonPress(when, policyFlags);
1599 }
1600
1601 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1602 mCurrentMotionAborted = false;
1603 }
1604 }
1605
1606 // Synthesize key up from raw buttons if needed.
1607 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1608 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1609 mCurrentCookedState.buttonState);
1610
1611 // Clear some transient state.
1612 mCurrentRawState.rawVScroll = 0;
1613 mCurrentRawState.rawHScroll = 0;
1614
1615 // Copy current touch to last touch in preparation for the next cycle.
1616 mLastRawState.copyFrom(mCurrentRawState);
1617 mLastCookedState.copyFrom(mCurrentCookedState);
1618}
1619
Garfield Tanc734e4f2021-01-15 20:01:39 -08001620void TouchInputMapper::updateTouchSpots() {
1621 if (!mConfig.showTouches || mPointerController == nullptr) {
1622 return;
1623 }
1624
1625 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1626 // clear touch spots.
1627 if (mDeviceMode != DeviceMode::DIRECT &&
1628 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1629 return;
1630 }
1631
1632 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1633 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1634
1635 mPointerController->setButtonState(mCurrentRawState.buttonState);
1636 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1637 mCurrentCookedState.cookedPointerData.idToIndex,
1638 mCurrentCookedState.cookedPointerData.touchingIdBits,
1639 mViewport.displayId);
1640}
1641
1642bool TouchInputMapper::isTouchScreen() {
1643 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1644 mParameters.hasAssociatedDisplay;
1645}
1646
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001648 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001649 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1650 }
1651}
1652
1653void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1654 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1655 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1656
1657 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1658 float pressure = mExternalStylusState.pressure;
1659 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1660 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1661 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1662 }
1663 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1664 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1665
1666 PointerProperties& properties =
1667 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1668 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1669 properties.toolType = mExternalStylusState.toolType;
1670 }
1671 }
1672}
1673
1674bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001675 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001676 return false;
1677 }
1678
1679 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1680 state.rawPointerData.pointerCount != 0;
1681 if (initialDown) {
1682 if (mExternalStylusState.pressure != 0.0f) {
1683#if DEBUG_STYLUS_FUSION
1684 ALOGD("Have both stylus and touch data, beginning fusion");
1685#endif
1686 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1687 } else if (timeout) {
1688#if DEBUG_STYLUS_FUSION
1689 ALOGD("Timeout expired, assuming touch is not a stylus.");
1690#endif
1691 resetExternalStylus();
1692 } else {
1693 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1694 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1695 }
1696#if DEBUG_STYLUS_FUSION
1697 ALOGD("No stylus data but stylus is connected, requesting timeout "
1698 "(%" PRId64 "ms)",
1699 mExternalStylusFusionTimeout);
1700#endif
1701 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1702 return true;
1703 }
1704 }
1705
1706 // Check if the stylus pointer has gone up.
1707 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1708#if DEBUG_STYLUS_FUSION
1709 ALOGD("Stylus pointer is going up");
1710#endif
1711 mExternalStylusId = -1;
1712 }
1713
1714 return false;
1715}
1716
1717void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001718 if (mDeviceMode == DeviceMode::POINTER) {
1719 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001720 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1721 }
Michael Wright227c5542020-07-02 18:30:52 +01001722 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001723 if (mExternalStylusFusionTimeout < when) {
1724 processRawTouches(true /*timeout*/);
1725 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1726 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1727 }
1728 }
1729}
1730
1731void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1732 mExternalStylusState.copyFrom(state);
1733 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1734 // We're either in the middle of a fused stream of data or we're waiting on data before
1735 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1736 // data.
1737 mExternalStylusDataPending = true;
1738 processRawTouches(false /*timeout*/);
1739 }
1740}
1741
1742bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1743 // Check for release of a virtual key.
1744 if (mCurrentVirtualKey.down) {
1745 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1746 // Pointer went up while virtual key was down.
1747 mCurrentVirtualKey.down = false;
1748 if (!mCurrentVirtualKey.ignored) {
1749#if DEBUG_VIRTUAL_KEYS
1750 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1751 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1752#endif
1753 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1754 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1755 }
1756 return true;
1757 }
1758
1759 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1760 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1761 const RawPointerData::Pointer& pointer =
1762 mCurrentRawState.rawPointerData.pointerForId(id);
1763 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1764 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1765 // Pointer is still within the space of the virtual key.
1766 return true;
1767 }
1768 }
1769
1770 // Pointer left virtual key area or another pointer also went down.
1771 // Send key cancellation but do not consume the touch yet.
1772 // This is useful when the user swipes through from the virtual key area
1773 // into the main display surface.
1774 mCurrentVirtualKey.down = false;
1775 if (!mCurrentVirtualKey.ignored) {
1776#if DEBUG_VIRTUAL_KEYS
1777 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1778 mCurrentVirtualKey.scanCode);
1779#endif
1780 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1781 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1782 AKEY_EVENT_FLAG_CANCELED);
1783 }
1784 }
1785
1786 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1787 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1788 // Pointer just went down. Check for virtual key press or off-screen touches.
1789 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1790 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001791 // Exclude unscaled device for inside surface checking.
1792 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793 // If exactly one pointer went down, check for virtual key hit.
1794 // Otherwise we will drop the entire stroke.
1795 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1796 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1797 if (virtualKey) {
1798 mCurrentVirtualKey.down = true;
1799 mCurrentVirtualKey.downTime = when;
1800 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1801 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1802 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001803 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1804 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001805
1806 if (!mCurrentVirtualKey.ignored) {
1807#if DEBUG_VIRTUAL_KEYS
1808 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1809 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1810#endif
1811 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1812 AKEY_EVENT_FLAG_FROM_SYSTEM |
1813 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1814 }
1815 }
1816 }
1817 return true;
1818 }
1819 }
1820
1821 // Disable all virtual key touches that happen within a short time interval of the
1822 // most recent touch within the screen area. The idea is to filter out stray
1823 // virtual key presses when interacting with the touch screen.
1824 //
1825 // Problems we're trying to solve:
1826 //
1827 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1828 // virtual key area that is implemented by a separate touch panel and accidentally
1829 // triggers a virtual key.
1830 //
1831 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1832 // area and accidentally triggers a virtual key. This often happens when virtual keys
1833 // are layed out below the screen near to where the on screen keyboard's space bar
1834 // is displayed.
1835 if (mConfig.virtualKeyQuietTime > 0 &&
1836 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001837 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001838 }
1839 return false;
1840}
1841
1842void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1843 int32_t keyEventAction, int32_t keyEventFlags) {
1844 int32_t keyCode = mCurrentVirtualKey.keyCode;
1845 int32_t scanCode = mCurrentVirtualKey.scanCode;
1846 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001847 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001848 policyFlags |= POLICY_FLAG_VIRTUAL;
1849
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06001850 getContext()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
1851 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode,
1852 metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001853}
1854
1855void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1856 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1857 if (!currentIdBits.isEmpty()) {
1858 int32_t metaState = getContext()->getGlobalMetaState();
1859 int32_t buttonState = mCurrentCookedState.buttonState;
1860 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1861 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1862 mCurrentCookedState.cookedPointerData.pointerProperties,
1863 mCurrentCookedState.cookedPointerData.pointerCoords,
1864 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1865 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1866 mCurrentMotionAborted = true;
1867 }
1868}
1869
1870void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1871 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1872 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1873 int32_t metaState = getContext()->getGlobalMetaState();
1874 int32_t buttonState = mCurrentCookedState.buttonState;
1875
1876 if (currentIdBits == lastIdBits) {
1877 if (!currentIdBits.isEmpty()) {
1878 // No pointer id changes so this is a move event.
1879 // The listener takes care of batching moves so we don't have to deal with that here.
1880 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1881 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1882 mCurrentCookedState.cookedPointerData.pointerProperties,
1883 mCurrentCookedState.cookedPointerData.pointerCoords,
1884 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1885 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1886 }
1887 } else {
1888 // There may be pointers going up and pointers going down and pointers moving
1889 // all at the same time.
1890 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1891 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1892 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1893 BitSet32 dispatchedIdBits(lastIdBits.value);
1894
1895 // Update last coordinates of pointers that have moved so that we observe the new
1896 // pointer positions at the same time as other pointers that have just gone up.
1897 bool moveNeeded =
1898 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1899 mCurrentCookedState.cookedPointerData.pointerCoords,
1900 mCurrentCookedState.cookedPointerData.idToIndex,
1901 mLastCookedState.cookedPointerData.pointerProperties,
1902 mLastCookedState.cookedPointerData.pointerCoords,
1903 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1904 if (buttonState != mLastCookedState.buttonState) {
1905 moveNeeded = true;
1906 }
1907
1908 // Dispatch pointer up events.
1909 while (!upIdBits.isEmpty()) {
1910 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001911 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1912 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1913 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001914 mLastCookedState.cookedPointerData.pointerProperties,
1915 mLastCookedState.cookedPointerData.pointerCoords,
1916 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1917 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1918 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001919 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001920 }
1921
1922 // Dispatch move events if any of the remaining pointers moved from their old locations.
1923 // Although applications receive new locations as part of individual pointer up
1924 // events, they do not generally handle them except when presented in a move event.
1925 if (moveNeeded && !moveIdBits.isEmpty()) {
1926 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1927 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1928 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1929 mCurrentCookedState.cookedPointerData.pointerCoords,
1930 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1931 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1932 }
1933
1934 // Dispatch pointer down events using the new pointer locations.
1935 while (!downIdBits.isEmpty()) {
1936 uint32_t downId = downIdBits.clearFirstMarkedBit();
1937 dispatchedIdBits.markBit(downId);
1938
1939 if (dispatchedIdBits.count() == 1) {
1940 // First pointer is going down. Set down time.
1941 mDownTime = when;
1942 }
1943
1944 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1945 metaState, buttonState, 0,
1946 mCurrentCookedState.cookedPointerData.pointerProperties,
1947 mCurrentCookedState.cookedPointerData.pointerCoords,
1948 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1949 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1950 }
1951 }
1952}
1953
1954void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1955 if (mSentHoverEnter &&
1956 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1957 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1958 int32_t metaState = getContext()->getGlobalMetaState();
1959 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1960 mLastCookedState.buttonState, 0,
1961 mLastCookedState.cookedPointerData.pointerProperties,
1962 mLastCookedState.cookedPointerData.pointerCoords,
1963 mLastCookedState.cookedPointerData.idToIndex,
1964 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1965 mOrientedYPrecision, mDownTime);
1966 mSentHoverEnter = false;
1967 }
1968}
1969
1970void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1971 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1972 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1973 int32_t metaState = getContext()->getGlobalMetaState();
1974 if (!mSentHoverEnter) {
1975 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1976 metaState, mCurrentRawState.buttonState, 0,
1977 mCurrentCookedState.cookedPointerData.pointerProperties,
1978 mCurrentCookedState.cookedPointerData.pointerCoords,
1979 mCurrentCookedState.cookedPointerData.idToIndex,
1980 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1981 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1982 mSentHoverEnter = true;
1983 }
1984
1985 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1986 mCurrentRawState.buttonState, 0,
1987 mCurrentCookedState.cookedPointerData.pointerProperties,
1988 mCurrentCookedState.cookedPointerData.pointerCoords,
1989 mCurrentCookedState.cookedPointerData.idToIndex,
1990 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1991 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1992 }
1993}
1994
1995void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1996 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1997 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1998 const int32_t metaState = getContext()->getGlobalMetaState();
1999 int32_t buttonState = mLastCookedState.buttonState;
2000 while (!releasedButtons.isEmpty()) {
2001 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2002 buttonState &= ~actionButton;
2003 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2004 actionButton, 0, metaState, buttonState, 0,
2005 mCurrentCookedState.cookedPointerData.pointerProperties,
2006 mCurrentCookedState.cookedPointerData.pointerCoords,
2007 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2008 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2009 }
2010}
2011
2012void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2013 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2014 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2015 const int32_t metaState = getContext()->getGlobalMetaState();
2016 int32_t buttonState = mLastCookedState.buttonState;
2017 while (!pressedButtons.isEmpty()) {
2018 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2019 buttonState |= actionButton;
2020 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2021 0, metaState, buttonState, 0,
2022 mCurrentCookedState.cookedPointerData.pointerProperties,
2023 mCurrentCookedState.cookedPointerData.pointerCoords,
2024 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2025 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2026 }
2027}
2028
2029const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2030 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2031 return cookedPointerData.touchingIdBits;
2032 }
2033 return cookedPointerData.hoveringIdBits;
2034}
2035
2036void TouchInputMapper::cookPointerData() {
2037 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2038
2039 mCurrentCookedState.cookedPointerData.clear();
2040 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2041 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2042 mCurrentRawState.rawPointerData.hoveringIdBits;
2043 mCurrentCookedState.cookedPointerData.touchingIdBits =
2044 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002045 mCurrentCookedState.cookedPointerData.canceledIdBits =
2046 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002047
2048 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2049 mCurrentCookedState.buttonState = 0;
2050 } else {
2051 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2052 }
2053
2054 // Walk through the the active pointers and map device coordinates onto
2055 // surface coordinates and adjust for display orientation.
2056 for (uint32_t i = 0; i < currentPointerCount; i++) {
2057 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2058
2059 // Size
2060 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2061 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002062 case Calibration::SizeCalibration::GEOMETRIC:
2063 case Calibration::SizeCalibration::DIAMETER:
2064 case Calibration::SizeCalibration::BOX:
2065 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002066 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2067 touchMajor = in.touchMajor;
2068 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2069 toolMajor = in.toolMajor;
2070 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2071 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2072 : in.touchMajor;
2073 } else if (mRawPointerAxes.touchMajor.valid) {
2074 toolMajor = touchMajor = in.touchMajor;
2075 toolMinor = touchMinor =
2076 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2077 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2078 : in.touchMajor;
2079 } else if (mRawPointerAxes.toolMajor.valid) {
2080 touchMajor = toolMajor = in.toolMajor;
2081 touchMinor = toolMinor =
2082 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2083 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2084 : in.toolMajor;
2085 } else {
2086 ALOG_ASSERT(false,
2087 "No touch or tool axes. "
2088 "Size calibration should have been resolved to NONE.");
2089 touchMajor = 0;
2090 touchMinor = 0;
2091 toolMajor = 0;
2092 toolMinor = 0;
2093 size = 0;
2094 }
2095
2096 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2097 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2098 if (touchingCount > 1) {
2099 touchMajor /= touchingCount;
2100 touchMinor /= touchingCount;
2101 toolMajor /= touchingCount;
2102 toolMinor /= touchingCount;
2103 size /= touchingCount;
2104 }
2105 }
2106
Michael Wright227c5542020-07-02 18:30:52 +01002107 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002108 touchMajor *= mGeometricScale;
2109 touchMinor *= mGeometricScale;
2110 toolMajor *= mGeometricScale;
2111 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002112 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2114 touchMinor = touchMajor;
2115 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2116 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002117 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002118 touchMinor = touchMajor;
2119 toolMinor = toolMajor;
2120 }
2121
2122 mCalibration.applySizeScaleAndBias(&touchMajor);
2123 mCalibration.applySizeScaleAndBias(&touchMinor);
2124 mCalibration.applySizeScaleAndBias(&toolMajor);
2125 mCalibration.applySizeScaleAndBias(&toolMinor);
2126 size *= mSizeScale;
2127 break;
2128 default:
2129 touchMajor = 0;
2130 touchMinor = 0;
2131 toolMajor = 0;
2132 toolMinor = 0;
2133 size = 0;
2134 break;
2135 }
2136
2137 // Pressure
2138 float pressure;
2139 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002140 case Calibration::PressureCalibration::PHYSICAL:
2141 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002142 pressure = in.pressure * mPressureScale;
2143 break;
2144 default:
2145 pressure = in.isHovering ? 0 : 1;
2146 break;
2147 }
2148
2149 // Tilt and Orientation
2150 float tilt;
2151 float orientation;
2152 if (mHaveTilt) {
2153 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2154 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2155 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2156 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2157 } else {
2158 tilt = 0;
2159
2160 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002161 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002162 orientation = in.orientation * mOrientationScale;
2163 break;
Michael Wright227c5542020-07-02 18:30:52 +01002164 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2166 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2167 if (c1 != 0 || c2 != 0) {
2168 orientation = atan2f(c1, c2) * 0.5f;
2169 float confidence = hypotf(c1, c2);
2170 float scale = 1.0f + confidence / 16.0f;
2171 touchMajor *= scale;
2172 touchMinor /= scale;
2173 toolMajor *= scale;
2174 toolMinor /= scale;
2175 } else {
2176 orientation = 0;
2177 }
2178 break;
2179 }
2180 default:
2181 orientation = 0;
2182 }
2183 }
2184
2185 // Distance
2186 float distance;
2187 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002188 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002189 distance = in.distance * mDistanceScale;
2190 break;
2191 default:
2192 distance = 0;
2193 }
2194
2195 // Coverage
2196 int32_t rawLeft, rawTop, rawRight, rawBottom;
2197 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002198 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002199 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2200 rawRight = in.toolMinor & 0x0000ffff;
2201 rawBottom = in.toolMajor & 0x0000ffff;
2202 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2203 break;
2204 default:
2205 rawLeft = rawTop = rawRight = rawBottom = 0;
2206 break;
2207 }
2208
2209 // Adjust X,Y coords for device calibration
2210 // TODO: Adjust coverage coords?
2211 float xTransformed = in.x, yTransformed = in.y;
2212 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002213 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002214
2215 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002216 float left, top, right, bottom;
2217
2218 switch (mSurfaceOrientation) {
2219 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002220 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2221 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2222 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2223 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2224 orientation -= M_PI_2;
2225 if (mOrientedRanges.haveOrientation &&
2226 orientation < mOrientedRanges.orientation.min) {
2227 orientation +=
2228 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2229 }
2230 break;
2231 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002232 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2233 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2234 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2235 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2236 orientation -= M_PI;
2237 if (mOrientedRanges.haveOrientation &&
2238 orientation < mOrientedRanges.orientation.min) {
2239 orientation +=
2240 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2241 }
2242 break;
2243 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2245 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2246 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2247 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2248 orientation += M_PI_2;
2249 if (mOrientedRanges.haveOrientation &&
2250 orientation > mOrientedRanges.orientation.max) {
2251 orientation -=
2252 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2253 }
2254 break;
2255 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2257 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2258 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2259 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2260 break;
2261 }
2262
2263 // Write output coords.
2264 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2265 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002266 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2267 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002268 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2269 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2270 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2271 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2272 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2273 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2274 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002275 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002276 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2277 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2278 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2279 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2280 } else {
2281 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2282 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2283 }
2284
Chris Ye364fdb52020-08-05 15:07:56 -07002285 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002286 uint32_t id = in.id;
2287 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2288 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2289 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2290 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2291 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2292 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2293 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2294 }
2295
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 // Write output properties.
2297 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002298 properties.clear();
2299 properties.id = id;
2300 properties.toolType = in.toolType;
2301
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002302 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002304 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002305 }
2306}
2307
2308void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2309 PointerUsage pointerUsage) {
2310 if (pointerUsage != mPointerUsage) {
2311 abortPointerUsage(when, policyFlags);
2312 mPointerUsage = pointerUsage;
2313 }
2314
2315 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002316 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2318 break;
Michael Wright227c5542020-07-02 18:30:52 +01002319 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 dispatchPointerStylus(when, policyFlags);
2321 break;
Michael Wright227c5542020-07-02 18:30:52 +01002322 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323 dispatchPointerMouse(when, policyFlags);
2324 break;
Michael Wright227c5542020-07-02 18:30:52 +01002325 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002326 break;
2327 }
2328}
2329
2330void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2331 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002332 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002333 abortPointerGestures(when, policyFlags);
2334 break;
Michael Wright227c5542020-07-02 18:30:52 +01002335 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002336 abortPointerStylus(when, policyFlags);
2337 break;
Michael Wright227c5542020-07-02 18:30:52 +01002338 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339 abortPointerMouse(when, policyFlags);
2340 break;
Michael Wright227c5542020-07-02 18:30:52 +01002341 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002342 break;
2343 }
2344
Michael Wright227c5542020-07-02 18:30:52 +01002345 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002346}
2347
2348void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2349 // Update current gesture coordinates.
2350 bool cancelPreviousGesture, finishPreviousGesture;
2351 bool sendEvents =
2352 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2353 if (!sendEvents) {
2354 return;
2355 }
2356 if (finishPreviousGesture) {
2357 cancelPreviousGesture = false;
2358 }
2359
2360 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002361 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002362 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002363 if (finishPreviousGesture || cancelPreviousGesture) {
2364 mPointerController->clearSpots();
2365 }
2366
Michael Wright227c5542020-07-02 18:30:52 +01002367 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2369 mPointerGesture.currentGestureIdToIndex,
2370 mPointerGesture.currentGestureIdBits,
2371 mPointerController->getDisplayId());
2372 }
2373 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002374 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 }
2376
2377 // Show or hide the pointer if needed.
2378 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002379 case PointerGesture::Mode::NEUTRAL:
2380 case PointerGesture::Mode::QUIET:
2381 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2382 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002384 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 }
2386 break;
Michael Wright227c5542020-07-02 18:30:52 +01002387 case PointerGesture::Mode::TAP:
2388 case PointerGesture::Mode::TAP_DRAG:
2389 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2390 case PointerGesture::Mode::HOVER:
2391 case PointerGesture::Mode::PRESS:
2392 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393 // Unfade the pointer when the current gesture manipulates the
2394 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002395 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 break;
Michael Wright227c5542020-07-02 18:30:52 +01002397 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 // Fade the pointer when the current gesture manipulates a different
2399 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002400 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002401 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002403 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 }
2405 break;
2406 }
2407
2408 // Send events!
2409 int32_t metaState = getContext()->getGlobalMetaState();
2410 int32_t buttonState = mCurrentCookedState.buttonState;
2411
2412 // Update last coordinates of pointers that have moved so that we observe the new
2413 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002414 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2415 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2416 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2417 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2418 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2419 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 bool moveNeeded = false;
2421 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2422 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2423 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2424 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2425 mPointerGesture.lastGestureIdBits.value);
2426 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2427 mPointerGesture.currentGestureCoords,
2428 mPointerGesture.currentGestureIdToIndex,
2429 mPointerGesture.lastGestureProperties,
2430 mPointerGesture.lastGestureCoords,
2431 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2432 if (buttonState != mLastCookedState.buttonState) {
2433 moveNeeded = true;
2434 }
2435 }
2436
2437 // Send motion events for all pointers that went up or were canceled.
2438 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2439 if (!dispatchedGestureIdBits.isEmpty()) {
2440 if (cancelPreviousGesture) {
2441 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2442 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2443 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2444 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2445 mPointerGesture.downTime);
2446
2447 dispatchedGestureIdBits.clear();
2448 } else {
2449 BitSet32 upGestureIdBits;
2450 if (finishPreviousGesture) {
2451 upGestureIdBits = dispatchedGestureIdBits;
2452 } else {
2453 upGestureIdBits.value =
2454 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2455 }
2456 while (!upGestureIdBits.isEmpty()) {
2457 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2458
2459 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2460 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2461 mPointerGesture.lastGestureProperties,
2462 mPointerGesture.lastGestureCoords,
2463 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2464 0, mPointerGesture.downTime);
2465
2466 dispatchedGestureIdBits.clearBit(id);
2467 }
2468 }
2469 }
2470
2471 // Send motion events for all pointers that moved.
2472 if (moveNeeded) {
2473 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2474 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2475 mPointerGesture.currentGestureProperties,
2476 mPointerGesture.currentGestureCoords,
2477 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2478 mPointerGesture.downTime);
2479 }
2480
2481 // Send motion events for all pointers that went down.
2482 if (down) {
2483 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2484 ~dispatchedGestureIdBits.value);
2485 while (!downGestureIdBits.isEmpty()) {
2486 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2487 dispatchedGestureIdBits.markBit(id);
2488
2489 if (dispatchedGestureIdBits.count() == 1) {
2490 mPointerGesture.downTime = when;
2491 }
2492
2493 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2494 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2495 mPointerGesture.currentGestureCoords,
2496 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2497 0, mPointerGesture.downTime);
2498 }
2499 }
2500
2501 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002502 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2504 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2505 mPointerGesture.currentGestureProperties,
2506 mPointerGesture.currentGestureCoords,
2507 mPointerGesture.currentGestureIdToIndex,
2508 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2509 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2510 // Synthesize a hover move event after all pointers go up to indicate that
2511 // the pointer is hovering again even if the user is not currently touching
2512 // the touch pad. This ensures that a view will receive a fresh hover enter
2513 // event after a tap.
2514 float x, y;
2515 mPointerController->getPosition(&x, &y);
2516
2517 PointerProperties pointerProperties;
2518 pointerProperties.clear();
2519 pointerProperties.id = 0;
2520 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2521
2522 PointerCoords pointerCoords;
2523 pointerCoords.clear();
2524 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2525 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2526
2527 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06002528 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
2529 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState,
2530 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
2531 &pointerProperties, &pointerCoords, 0, 0, x, y,
2532 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002533 }
2534
2535 // Update state.
2536 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2537 if (!down) {
2538 mPointerGesture.lastGestureIdBits.clear();
2539 } else {
2540 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2541 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2542 uint32_t id = idBits.clearFirstMarkedBit();
2543 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2544 mPointerGesture.lastGestureProperties[index].copyFrom(
2545 mPointerGesture.currentGestureProperties[index]);
2546 mPointerGesture.lastGestureCoords[index].copyFrom(
2547 mPointerGesture.currentGestureCoords[index]);
2548 mPointerGesture.lastGestureIdToIndex[id] = index;
2549 }
2550 }
2551}
2552
2553void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2554 // Cancel previously dispatches pointers.
2555 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2556 int32_t metaState = getContext()->getGlobalMetaState();
2557 int32_t buttonState = mCurrentRawState.buttonState;
2558 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2559 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2560 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2561 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2562 0, 0, mPointerGesture.downTime);
2563 }
2564
2565 // Reset the current pointer gesture.
2566 mPointerGesture.reset();
2567 mPointerVelocityControl.reset();
2568
2569 // Remove any current spots.
2570 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002571 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002572 mPointerController->clearSpots();
2573 }
2574}
2575
2576bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2577 bool* outFinishPreviousGesture, bool isTimeout) {
2578 *outCancelPreviousGesture = false;
2579 *outFinishPreviousGesture = false;
2580
2581 // Handle TAP timeout.
2582 if (isTimeout) {
2583#if DEBUG_GESTURES
2584 ALOGD("Gestures: Processing timeout");
2585#endif
2586
Michael Wright227c5542020-07-02 18:30:52 +01002587 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002588 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2589 // The tap/drag timeout has not yet expired.
2590 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2591 mConfig.pointerGestureTapDragInterval);
2592 } else {
2593 // The tap is finished.
2594#if DEBUG_GESTURES
2595 ALOGD("Gestures: TAP finished");
2596#endif
2597 *outFinishPreviousGesture = true;
2598
2599 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002600 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002601 mPointerGesture.currentGestureIdBits.clear();
2602
2603 mPointerVelocityControl.reset();
2604 return true;
2605 }
2606 }
2607
2608 // We did not handle this timeout.
2609 return false;
2610 }
2611
2612 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2613 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2614
2615 // Update the velocity tracker.
2616 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002617 std::vector<VelocityTracker::Position> positions;
2618 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002619 uint32_t id = idBits.clearFirstMarkedBit();
2620 const RawPointerData::Pointer& pointer =
2621 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002622 float x = pointer.x * mPointerXMovementScale;
2623 float y = pointer.y * mPointerYMovementScale;
2624 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002625 }
2626 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2627 positions);
2628 }
2629
2630 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2631 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002632 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2633 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2634 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002635 mPointerGesture.resetTap();
2636 }
2637
2638 // Pick a new active touch id if needed.
2639 // Choose an arbitrary pointer that just went down, if there is one.
2640 // Otherwise choose an arbitrary remaining pointer.
2641 // This guarantees we always have an active touch id when there is at least one pointer.
2642 // We keep the same active touch id for as long as possible.
2643 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2644 int32_t activeTouchId = lastActiveTouchId;
2645 if (activeTouchId < 0) {
2646 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2647 activeTouchId = mPointerGesture.activeTouchId =
2648 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2649 mPointerGesture.firstTouchTime = when;
2650 }
2651 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2652 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2653 activeTouchId = mPointerGesture.activeTouchId =
2654 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2655 } else {
2656 activeTouchId = mPointerGesture.activeTouchId = -1;
2657 }
2658 }
2659
2660 // Determine whether we are in quiet time.
2661 bool isQuietTime = false;
2662 if (activeTouchId < 0) {
2663 mPointerGesture.resetQuietTime();
2664 } else {
2665 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2666 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002667 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2668 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2669 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002670 currentFingerCount < 2) {
2671 // Enter quiet time when exiting swipe or freeform state.
2672 // This is to prevent accidentally entering the hover state and flinging the
2673 // pointer when finishing a swipe and there is still one pointer left onscreen.
2674 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002675 } else if (mPointerGesture.lastGestureMode ==
2676 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002677 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2678 // Enter quiet time when releasing the button and there are still two or more
2679 // fingers down. This may indicate that one finger was used to press the button
2680 // but it has not gone up yet.
2681 isQuietTime = true;
2682 }
2683 if (isQuietTime) {
2684 mPointerGesture.quietTime = when;
2685 }
2686 }
2687 }
2688
2689 // Switch states based on button and pointer state.
2690 if (isQuietTime) {
2691 // Case 1: Quiet time. (QUIET)
2692#if DEBUG_GESTURES
2693 ALOGD("Gestures: QUIET for next %0.3fms",
2694 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2695#endif
Michael Wright227c5542020-07-02 18:30:52 +01002696 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002697 *outFinishPreviousGesture = true;
2698 }
2699
2700 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002701 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002702 mPointerGesture.currentGestureIdBits.clear();
2703
2704 mPointerVelocityControl.reset();
2705 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2706 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2707 // The pointer follows the active touch point.
2708 // Emit DOWN, MOVE, UP events at the pointer location.
2709 //
2710 // Only the active touch matters; other fingers are ignored. This policy helps
2711 // to handle the case where the user places a second finger on the touch pad
2712 // to apply the necessary force to depress an integrated button below the surface.
2713 // We don't want the second finger to be delivered to applications.
2714 //
2715 // For this to work well, we need to make sure to track the pointer that is really
2716 // active. If the user first puts one finger down to click then adds another
2717 // finger to drag then the active pointer should switch to the finger that is
2718 // being dragged.
2719#if DEBUG_GESTURES
2720 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2721 "currentFingerCount=%d",
2722 activeTouchId, currentFingerCount);
2723#endif
2724 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002725 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002726 *outFinishPreviousGesture = true;
2727 mPointerGesture.activeGestureId = 0;
2728 }
2729
2730 // Switch pointers if needed.
2731 // Find the fastest pointer and follow it.
2732 if (activeTouchId >= 0 && currentFingerCount > 1) {
2733 int32_t bestId = -1;
2734 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2735 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2736 uint32_t id = idBits.clearFirstMarkedBit();
2737 float vx, vy;
2738 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2739 float speed = hypotf(vx, vy);
2740 if (speed > bestSpeed) {
2741 bestId = id;
2742 bestSpeed = speed;
2743 }
2744 }
2745 }
2746 if (bestId >= 0 && bestId != activeTouchId) {
2747 mPointerGesture.activeTouchId = activeTouchId = bestId;
2748#if DEBUG_GESTURES
2749 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2750 "bestId=%d, bestSpeed=%0.3f",
2751 bestId, bestSpeed);
2752#endif
2753 }
2754 }
2755
2756 float deltaX = 0, deltaY = 0;
2757 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2758 const RawPointerData::Pointer& currentPointer =
2759 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2760 const RawPointerData::Pointer& lastPointer =
2761 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2762 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2763 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2764
2765 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2766 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2767
2768 // Move the pointer using a relative motion.
2769 // When using spots, the click will occur at the position of the anchor
2770 // spot and all other spots will move there.
2771 mPointerController->move(deltaX, deltaY);
2772 } else {
2773 mPointerVelocityControl.reset();
2774 }
2775
2776 float x, y;
2777 mPointerController->getPosition(&x, &y);
2778
Michael Wright227c5542020-07-02 18:30:52 +01002779 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002780 mPointerGesture.currentGestureIdBits.clear();
2781 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2782 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2783 mPointerGesture.currentGestureProperties[0].clear();
2784 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2785 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2786 mPointerGesture.currentGestureCoords[0].clear();
2787 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2788 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2789 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2790 } else if (currentFingerCount == 0) {
2791 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002792 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002793 *outFinishPreviousGesture = true;
2794 }
2795
2796 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2797 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2798 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002799 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2800 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002801 lastFingerCount == 1) {
2802 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2803 float x, y;
2804 mPointerController->getPosition(&x, &y);
2805 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2806 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2807#if DEBUG_GESTURES
2808 ALOGD("Gestures: TAP");
2809#endif
2810
2811 mPointerGesture.tapUpTime = when;
2812 getContext()->requestTimeoutAtTime(when +
2813 mConfig.pointerGestureTapDragInterval);
2814
2815 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002816 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002817 mPointerGesture.currentGestureIdBits.clear();
2818 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2819 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2820 mPointerGesture.currentGestureProperties[0].clear();
2821 mPointerGesture.currentGestureProperties[0].id =
2822 mPointerGesture.activeGestureId;
2823 mPointerGesture.currentGestureProperties[0].toolType =
2824 AMOTION_EVENT_TOOL_TYPE_FINGER;
2825 mPointerGesture.currentGestureCoords[0].clear();
2826 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2827 mPointerGesture.tapX);
2828 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2829 mPointerGesture.tapY);
2830 mPointerGesture.currentGestureCoords[0]
2831 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2832
2833 tapped = true;
2834 } else {
2835#if DEBUG_GESTURES
2836 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2837 y - mPointerGesture.tapY);
2838#endif
2839 }
2840 } else {
2841#if DEBUG_GESTURES
2842 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2843 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2844 (when - mPointerGesture.tapDownTime) * 0.000001f);
2845 } else {
2846 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2847 }
2848#endif
2849 }
2850 }
2851
2852 mPointerVelocityControl.reset();
2853
2854 if (!tapped) {
2855#if DEBUG_GESTURES
2856 ALOGD("Gestures: NEUTRAL");
2857#endif
2858 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002859 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002860 mPointerGesture.currentGestureIdBits.clear();
2861 }
2862 } else if (currentFingerCount == 1) {
2863 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2864 // The pointer follows the active touch point.
2865 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2866 // When in TAP_DRAG, emit MOVE events at the pointer location.
2867 ALOG_ASSERT(activeTouchId >= 0);
2868
Michael Wright227c5542020-07-02 18:30:52 +01002869 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2870 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002871 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2872 float x, y;
2873 mPointerController->getPosition(&x, &y);
2874 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2875 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002876 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002877 } else {
2878#if DEBUG_GESTURES
2879 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2880 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2881#endif
2882 }
2883 } else {
2884#if DEBUG_GESTURES
2885 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2886 (when - mPointerGesture.tapUpTime) * 0.000001f);
2887#endif
2888 }
Michael Wright227c5542020-07-02 18:30:52 +01002889 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2890 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 }
2892
2893 float deltaX = 0, deltaY = 0;
2894 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2895 const RawPointerData::Pointer& currentPointer =
2896 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2897 const RawPointerData::Pointer& lastPointer =
2898 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2899 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2900 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2901
2902 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2903 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2904
2905 // Move the pointer using a relative motion.
2906 // When using spots, the hover or drag will occur at the position of the anchor spot.
2907 mPointerController->move(deltaX, deltaY);
2908 } else {
2909 mPointerVelocityControl.reset();
2910 }
2911
2912 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002913 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002914#if DEBUG_GESTURES
2915 ALOGD("Gestures: TAP_DRAG");
2916#endif
2917 down = true;
2918 } else {
2919#if DEBUG_GESTURES
2920 ALOGD("Gestures: HOVER");
2921#endif
Michael Wright227c5542020-07-02 18:30:52 +01002922 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002923 *outFinishPreviousGesture = true;
2924 }
2925 mPointerGesture.activeGestureId = 0;
2926 down = false;
2927 }
2928
2929 float x, y;
2930 mPointerController->getPosition(&x, &y);
2931
2932 mPointerGesture.currentGestureIdBits.clear();
2933 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2934 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2935 mPointerGesture.currentGestureProperties[0].clear();
2936 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2937 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2938 mPointerGesture.currentGestureCoords[0].clear();
2939 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2940 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2941 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2942 down ? 1.0f : 0.0f);
2943
2944 if (lastFingerCount == 0 && currentFingerCount != 0) {
2945 mPointerGesture.resetTap();
2946 mPointerGesture.tapDownTime = when;
2947 mPointerGesture.tapX = x;
2948 mPointerGesture.tapY = y;
2949 }
2950 } else {
2951 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2952 // We need to provide feedback for each finger that goes down so we cannot wait
2953 // for the fingers to move before deciding what to do.
2954 //
2955 // The ambiguous case is deciding what to do when there are two fingers down but they
2956 // have not moved enough to determine whether they are part of a drag or part of a
2957 // freeform gesture, or just a press or long-press at the pointer location.
2958 //
2959 // When there are two fingers we start with the PRESS hypothesis and we generate a
2960 // down at the pointer location.
2961 //
2962 // When the two fingers move enough or when additional fingers are added, we make
2963 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2964 ALOG_ASSERT(activeTouchId >= 0);
2965
2966 bool settled = when >=
2967 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002968 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2969 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2970 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002971 *outFinishPreviousGesture = true;
2972 } else if (!settled && currentFingerCount > lastFingerCount) {
2973 // Additional pointers have gone down but not yet settled.
2974 // Reset the gesture.
2975#if DEBUG_GESTURES
2976 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2977 "settle time remaining %0.3fms",
2978 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2979 when) * 0.000001f);
2980#endif
2981 *outCancelPreviousGesture = true;
2982 } else {
2983 // Continue previous gesture.
2984 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2985 }
2986
2987 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002988 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 mPointerGesture.activeGestureId = 0;
2990 mPointerGesture.referenceIdBits.clear();
2991 mPointerVelocityControl.reset();
2992
2993 // Use the centroid and pointer location as the reference points for the gesture.
2994#if DEBUG_GESTURES
2995 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2996 "settle time remaining %0.3fms",
2997 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2998 when) * 0.000001f);
2999#endif
3000 mCurrentRawState.rawPointerData
3001 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3002 &mPointerGesture.referenceTouchY);
3003 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3004 &mPointerGesture.referenceGestureY);
3005 }
3006
3007 // Clear the reference deltas for fingers not yet included in the reference calculation.
3008 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3009 ~mPointerGesture.referenceIdBits.value);
3010 !idBits.isEmpty();) {
3011 uint32_t id = idBits.clearFirstMarkedBit();
3012 mPointerGesture.referenceDeltas[id].dx = 0;
3013 mPointerGesture.referenceDeltas[id].dy = 0;
3014 }
3015 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3016
3017 // Add delta for all fingers and calculate a common movement delta.
3018 float commonDeltaX = 0, commonDeltaY = 0;
3019 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3020 mCurrentCookedState.fingerIdBits.value);
3021 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3022 bool first = (idBits == commonIdBits);
3023 uint32_t id = idBits.clearFirstMarkedBit();
3024 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3025 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3026 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3027 delta.dx += cpd.x - lpd.x;
3028 delta.dy += cpd.y - lpd.y;
3029
3030 if (first) {
3031 commonDeltaX = delta.dx;
3032 commonDeltaY = delta.dy;
3033 } else {
3034 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3035 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3036 }
3037 }
3038
3039 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003040 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003041 float dist[MAX_POINTER_ID + 1];
3042 int32_t distOverThreshold = 0;
3043 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3044 uint32_t id = idBits.clearFirstMarkedBit();
3045 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3046 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3047 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3048 distOverThreshold += 1;
3049 }
3050 }
3051
3052 // Only transition when at least two pointers have moved further than
3053 // the minimum distance threshold.
3054 if (distOverThreshold >= 2) {
3055 if (currentFingerCount > 2) {
3056 // There are more than two pointers, switch to FREEFORM.
3057#if DEBUG_GESTURES
3058 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3059 currentFingerCount);
3060#endif
3061 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003062 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003063 } else {
3064 // There are exactly two pointers.
3065 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3066 uint32_t id1 = idBits.clearFirstMarkedBit();
3067 uint32_t id2 = idBits.firstMarkedBit();
3068 const RawPointerData::Pointer& p1 =
3069 mCurrentRawState.rawPointerData.pointerForId(id1);
3070 const RawPointerData::Pointer& p2 =
3071 mCurrentRawState.rawPointerData.pointerForId(id2);
3072 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3073 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3074 // There are two pointers but they are too far apart for a SWIPE,
3075 // switch to FREEFORM.
3076#if DEBUG_GESTURES
3077 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3078 mutualDistance, mPointerGestureMaxSwipeWidth);
3079#endif
3080 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003081 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003082 } else {
3083 // There are two pointers. Wait for both pointers to start moving
3084 // before deciding whether this is a SWIPE or FREEFORM gesture.
3085 float dist1 = dist[id1];
3086 float dist2 = dist[id2];
3087 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3088 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3089 // Calculate the dot product of the displacement vectors.
3090 // When the vectors are oriented in approximately the same direction,
3091 // the angle betweeen them is near zero and the cosine of the angle
3092 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3093 // mag(v2).
3094 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3095 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3096 float dx1 = delta1.dx * mPointerXZoomScale;
3097 float dy1 = delta1.dy * mPointerYZoomScale;
3098 float dx2 = delta2.dx * mPointerXZoomScale;
3099 float dy2 = delta2.dy * mPointerYZoomScale;
3100 float dot = dx1 * dx2 + dy1 * dy2;
3101 float cosine = dot / (dist1 * dist2); // denominator always > 0
3102 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3103 // Pointers are moving in the same direction. Switch to SWIPE.
3104#if DEBUG_GESTURES
3105 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3106 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3107 "cosine %0.3f >= %0.3f",
3108 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3109 mConfig.pointerGestureMultitouchMinDistance, cosine,
3110 mConfig.pointerGestureSwipeTransitionAngleCosine);
3111#endif
Michael Wright227c5542020-07-02 18:30:52 +01003112 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003113 } else {
3114 // Pointers are moving in different directions. Switch to FREEFORM.
3115#if DEBUG_GESTURES
3116 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3117 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3118 "cosine %0.3f < %0.3f",
3119 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3120 mConfig.pointerGestureMultitouchMinDistance, cosine,
3121 mConfig.pointerGestureSwipeTransitionAngleCosine);
3122#endif
3123 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003124 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003125 }
3126 }
3127 }
3128 }
3129 }
Michael Wright227c5542020-07-02 18:30:52 +01003130 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003131 // Switch from SWIPE to FREEFORM if additional pointers go down.
3132 // Cancel previous gesture.
3133 if (currentFingerCount > 2) {
3134#if DEBUG_GESTURES
3135 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3136 currentFingerCount);
3137#endif
3138 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003139 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003140 }
3141 }
3142
3143 // Move the reference points based on the overall group motion of the fingers
3144 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003145 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003146 (commonDeltaX || commonDeltaY)) {
3147 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3148 uint32_t id = idBits.clearFirstMarkedBit();
3149 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3150 delta.dx = 0;
3151 delta.dy = 0;
3152 }
3153
3154 mPointerGesture.referenceTouchX += commonDeltaX;
3155 mPointerGesture.referenceTouchY += commonDeltaY;
3156
3157 commonDeltaX *= mPointerXMovementScale;
3158 commonDeltaY *= mPointerYMovementScale;
3159
3160 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3161 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3162
3163 mPointerGesture.referenceGestureX += commonDeltaX;
3164 mPointerGesture.referenceGestureY += commonDeltaY;
3165 }
3166
3167 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003168 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3169 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003170 // PRESS or SWIPE mode.
3171#if DEBUG_GESTURES
3172 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3173 "activeGestureId=%d, currentTouchPointerCount=%d",
3174 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3175#endif
3176 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3177
3178 mPointerGesture.currentGestureIdBits.clear();
3179 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3180 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3181 mPointerGesture.currentGestureProperties[0].clear();
3182 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3183 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3184 mPointerGesture.currentGestureCoords[0].clear();
3185 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3186 mPointerGesture.referenceGestureX);
3187 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3188 mPointerGesture.referenceGestureY);
3189 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003190 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003191 // FREEFORM mode.
3192#if DEBUG_GESTURES
3193 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3194 "activeGestureId=%d, currentTouchPointerCount=%d",
3195 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3196#endif
3197 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3198
3199 mPointerGesture.currentGestureIdBits.clear();
3200
3201 BitSet32 mappedTouchIdBits;
3202 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003203 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003204 // Initially, assign the active gesture id to the active touch point
3205 // if there is one. No other touch id bits are mapped yet.
3206 if (!*outCancelPreviousGesture) {
3207 mappedTouchIdBits.markBit(activeTouchId);
3208 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3209 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3210 mPointerGesture.activeGestureId;
3211 } else {
3212 mPointerGesture.activeGestureId = -1;
3213 }
3214 } else {
3215 // Otherwise, assume we mapped all touches from the previous frame.
3216 // Reuse all mappings that are still applicable.
3217 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3218 mCurrentCookedState.fingerIdBits.value;
3219 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3220
3221 // Check whether we need to choose a new active gesture id because the
3222 // current went went up.
3223 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3224 ~mCurrentCookedState.fingerIdBits.value);
3225 !upTouchIdBits.isEmpty();) {
3226 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3227 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3228 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3229 mPointerGesture.activeGestureId = -1;
3230 break;
3231 }
3232 }
3233 }
3234
3235#if DEBUG_GESTURES
3236 ALOGD("Gestures: FREEFORM follow up "
3237 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3238 "activeGestureId=%d",
3239 mappedTouchIdBits.value, usedGestureIdBits.value,
3240 mPointerGesture.activeGestureId);
3241#endif
3242
3243 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3244 for (uint32_t i = 0; i < currentFingerCount; i++) {
3245 uint32_t touchId = idBits.clearFirstMarkedBit();
3246 uint32_t gestureId;
3247 if (!mappedTouchIdBits.hasBit(touchId)) {
3248 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3249 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3250#if DEBUG_GESTURES
3251 ALOGD("Gestures: FREEFORM "
3252 "new mapping for touch id %d -> gesture id %d",
3253 touchId, gestureId);
3254#endif
3255 } else {
3256 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3257#if DEBUG_GESTURES
3258 ALOGD("Gestures: FREEFORM "
3259 "existing mapping for touch id %d -> gesture id %d",
3260 touchId, gestureId);
3261#endif
3262 }
3263 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3264 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3265
3266 const RawPointerData::Pointer& pointer =
3267 mCurrentRawState.rawPointerData.pointerForId(touchId);
3268 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3269 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3270 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3271
3272 mPointerGesture.currentGestureProperties[i].clear();
3273 mPointerGesture.currentGestureProperties[i].id = gestureId;
3274 mPointerGesture.currentGestureProperties[i].toolType =
3275 AMOTION_EVENT_TOOL_TYPE_FINGER;
3276 mPointerGesture.currentGestureCoords[i].clear();
3277 mPointerGesture.currentGestureCoords[i]
3278 .setAxisValue(AMOTION_EVENT_AXIS_X,
3279 mPointerGesture.referenceGestureX + deltaX);
3280 mPointerGesture.currentGestureCoords[i]
3281 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3282 mPointerGesture.referenceGestureY + deltaY);
3283 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3284 1.0f);
3285 }
3286
3287 if (mPointerGesture.activeGestureId < 0) {
3288 mPointerGesture.activeGestureId =
3289 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3290#if DEBUG_GESTURES
3291 ALOGD("Gestures: FREEFORM new "
3292 "activeGestureId=%d",
3293 mPointerGesture.activeGestureId);
3294#endif
3295 }
3296 }
3297 }
3298
3299 mPointerController->setButtonState(mCurrentRawState.buttonState);
3300
3301#if DEBUG_GESTURES
3302 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3303 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3304 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3305 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3306 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3307 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3308 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3309 uint32_t id = idBits.clearFirstMarkedBit();
3310 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3311 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3312 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3313 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3314 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3315 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3316 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3317 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3318 }
3319 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3320 uint32_t id = idBits.clearFirstMarkedBit();
3321 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3322 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3323 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3324 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3325 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3326 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3327 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3328 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3329 }
3330#endif
3331 return true;
3332}
3333
3334void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3335 mPointerSimple.currentCoords.clear();
3336 mPointerSimple.currentProperties.clear();
3337
3338 bool down, hovering;
3339 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3340 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3341 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3342 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3343 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3344 mPointerController->setPosition(x, y);
3345
3346 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3347 down = !hovering;
3348
3349 mPointerController->getPosition(&x, &y);
3350 mPointerSimple.currentCoords.copyFrom(
3351 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3352 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3353 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3354 mPointerSimple.currentProperties.id = 0;
3355 mPointerSimple.currentProperties.toolType =
3356 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3357 } else {
3358 down = false;
3359 hovering = false;
3360 }
3361
3362 dispatchPointerSimple(when, policyFlags, down, hovering);
3363}
3364
3365void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3366 abortPointerSimple(when, policyFlags);
3367}
3368
3369void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3370 mPointerSimple.currentCoords.clear();
3371 mPointerSimple.currentProperties.clear();
3372
3373 bool down, hovering;
3374 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3375 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3376 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3377 float deltaX = 0, deltaY = 0;
3378 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3379 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3380 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3381 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3382 mPointerXMovementScale;
3383 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3384 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3385 mPointerYMovementScale;
3386
3387 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3388 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3389
3390 mPointerController->move(deltaX, deltaY);
3391 } else {
3392 mPointerVelocityControl.reset();
3393 }
3394
3395 down = isPointerDown(mCurrentRawState.buttonState);
3396 hovering = !down;
3397
3398 float x, y;
3399 mPointerController->getPosition(&x, &y);
3400 mPointerSimple.currentCoords.copyFrom(
3401 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3402 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3403 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3404 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3405 hovering ? 0.0f : 1.0f);
3406 mPointerSimple.currentProperties.id = 0;
3407 mPointerSimple.currentProperties.toolType =
3408 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3409 } else {
3410 mPointerVelocityControl.reset();
3411
3412 down = false;
3413 hovering = false;
3414 }
3415
3416 dispatchPointerSimple(when, policyFlags, down, hovering);
3417}
3418
3419void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3420 abortPointerSimple(when, policyFlags);
3421
3422 mPointerVelocityControl.reset();
3423}
3424
3425void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3426 bool hovering) {
3427 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003428
3429 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003430 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003431 mPointerController->clearSpots();
3432 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003433 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003434 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003435 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003436 }
Garfield Tan9514d782020-11-10 16:37:23 -08003437 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003438
3439 float xCursorPosition;
3440 float yCursorPosition;
3441 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3442
3443 if (mPointerSimple.down && !down) {
3444 mPointerSimple.down = false;
3445
3446 // Send up.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003447 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3448 AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
3449 mLastRawState.buttonState, MotionClassification::NONE,
3450 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3451 &mPointerSimple.lastCoords, mOrientedXPrecision,
3452 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3453 mPointerSimple.downTime,
3454 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003455 }
3456
3457 if (mPointerSimple.hovering && !hovering) {
3458 mPointerSimple.hovering = false;
3459
3460 // Send hover exit.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003461 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3462 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3463 mLastRawState.buttonState, MotionClassification::NONE,
3464 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3465 &mPointerSimple.lastCoords, mOrientedXPrecision,
3466 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3467 mPointerSimple.downTime,
3468 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469 }
3470
3471 if (down) {
3472 if (!mPointerSimple.down) {
3473 mPointerSimple.down = true;
3474 mPointerSimple.downTime = when;
3475
3476 // Send down.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003477 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3478 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3479 mCurrentRawState.buttonState, MotionClassification::NONE,
3480 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3481 &mPointerSimple.currentProperties,
3482 &mPointerSimple.currentCoords, mOrientedXPrecision,
3483 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3484 mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003485 }
3486
3487 // Send move.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003488 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3489 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
3490 mCurrentRawState.buttonState, MotionClassification::NONE,
3491 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3492 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3493 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3494 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003495 }
3496
3497 if (hovering) {
3498 if (!mPointerSimple.hovering) {
3499 mPointerSimple.hovering = true;
3500
3501 // Send hover enter.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003502 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3503 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3504 mCurrentRawState.buttonState, MotionClassification::NONE,
3505 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3506 &mPointerSimple.currentProperties,
3507 &mPointerSimple.currentCoords, mOrientedXPrecision,
3508 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3509 mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003510 }
3511
3512 // Send hover move.
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003513 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3514 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3515 mCurrentRawState.buttonState, MotionClassification::NONE,
3516 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3517 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3518 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3519 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003520 }
3521
3522 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3523 float vscroll = mCurrentRawState.rawVScroll;
3524 float hscroll = mCurrentRawState.rawHScroll;
3525 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3526 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3527
3528 // Send scroll.
3529 PointerCoords pointerCoords;
3530 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3531 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3532 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3533
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003534 getContext()->notifyMotion(when, getDeviceId(), mSource, displayId, policyFlags,
3535 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
3536 mCurrentRawState.buttonState, MotionClassification::NONE,
3537 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3538 &mPointerSimple.currentProperties, &pointerCoords,
3539 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3540 yCursorPosition, mPointerSimple.downTime,
3541 /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003542 }
3543
3544 // Save state.
3545 if (down || hovering) {
3546 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3547 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3548 } else {
3549 mPointerSimple.reset();
3550 }
3551}
3552
3553void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3554 mPointerSimple.currentCoords.clear();
3555 mPointerSimple.currentProperties.clear();
3556
3557 dispatchPointerSimple(when, policyFlags, false, false);
3558}
3559
3560void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3561 int32_t action, int32_t actionButton, int32_t flags,
3562 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3563 const PointerProperties* properties,
3564 const PointerCoords* coords, const uint32_t* idToIndex,
3565 BitSet32 idBits, int32_t changedId, float xPrecision,
3566 float yPrecision, nsecs_t downTime) {
3567 PointerCoords pointerCoords[MAX_POINTERS];
3568 PointerProperties pointerProperties[MAX_POINTERS];
3569 uint32_t pointerCount = 0;
3570 while (!idBits.isEmpty()) {
3571 uint32_t id = idBits.clearFirstMarkedBit();
3572 uint32_t index = idToIndex[id];
3573 pointerProperties[pointerCount].copyFrom(properties[index]);
3574 pointerCoords[pointerCount].copyFrom(coords[index]);
3575
3576 if (changedId >= 0 && id == uint32_t(changedId)) {
3577 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3578 }
3579
3580 pointerCount += 1;
3581 }
3582
3583 ALOG_ASSERT(pointerCount != 0);
3584
3585 if (changedId >= 0 && pointerCount == 1) {
3586 // Replace initial down and final up action.
3587 // We can compare the action without masking off the changed pointer index
3588 // because we know the index is 0.
3589 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3590 action = AMOTION_EVENT_ACTION_DOWN;
3591 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003592 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3593 action = AMOTION_EVENT_ACTION_CANCEL;
3594 } else {
3595 action = AMOTION_EVENT_ACTION_UP;
3596 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003597 } else {
3598 // Can't happen.
3599 ALOG_ASSERT(false);
3600 }
3601 }
3602 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3603 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003604 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003605 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3606 }
3607 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3608 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003609 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003610 std::for_each(frames.begin(), frames.end(),
3611 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakoucec3f6a2020-11-10 15:42:39 -06003612 getContext()->notifyMotion(when, deviceId, source, displayId, policyFlags, action, actionButton,
3613 flags, metaState, buttonState, MotionClassification::NONE, edgeFlags,
3614 pointerCount, pointerProperties, pointerCoords, xPrecision,
3615 yPrecision, xCursorPosition, yCursorPosition, downTime,
3616 std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003617}
3618
3619bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3620 const PointerCoords* inCoords,
3621 const uint32_t* inIdToIndex,
3622 PointerProperties* outProperties,
3623 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3624 BitSet32 idBits) const {
3625 bool changed = false;
3626 while (!idBits.isEmpty()) {
3627 uint32_t id = idBits.clearFirstMarkedBit();
3628 uint32_t inIndex = inIdToIndex[id];
3629 uint32_t outIndex = outIdToIndex[id];
3630
3631 const PointerProperties& curInProperties = inProperties[inIndex];
3632 const PointerCoords& curInCoords = inCoords[inIndex];
3633 PointerProperties& curOutProperties = outProperties[outIndex];
3634 PointerCoords& curOutCoords = outCoords[outIndex];
3635
3636 if (curInProperties != curOutProperties) {
3637 curOutProperties.copyFrom(curInProperties);
3638 changed = true;
3639 }
3640
3641 if (curInCoords != curOutCoords) {
3642 curOutCoords.copyFrom(curInCoords);
3643 changed = true;
3644 }
3645 }
3646 return changed;
3647}
3648
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003649void TouchInputMapper::cancelTouch(nsecs_t when) {
3650 abortPointerUsage(when, 0 /*policyFlags*/);
3651 abortTouches(when, 0 /* policyFlags*/);
3652}
3653
Arthur Hung4197f6b2020-03-16 15:39:59 +08003654// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003655void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003656 // Scale to surface coordinate.
3657 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3658 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3659
arthurhunga36b28e2020-12-29 20:28:15 +08003660 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3661 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3662
Arthur Hung4197f6b2020-03-16 15:39:59 +08003663 // Rotate to surface coordinate.
3664 // 0 - no swap and reverse.
3665 // 90 - swap x/y and reverse y.
3666 // 180 - reverse x, y.
3667 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003668 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003669 case DISPLAY_ORIENTATION_0:
3670 x = xScaled + mXTranslate;
3671 y = yScaled + mYTranslate;
3672 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003673 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003674 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003675 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003676 break;
3677 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003678 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3679 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003680 break;
3681 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003682 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003683 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003684 break;
3685 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003686 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003687 }
3688}
3689
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003690bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003691 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3692 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3693
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003694 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003695 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003697 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003698}
3699
3700const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3701 for (const VirtualKey& virtualKey : mVirtualKeys) {
3702#if DEBUG_VIRTUAL_KEYS
3703 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3704 "left=%d, top=%d, right=%d, bottom=%d",
3705 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3706 virtualKey.hitRight, virtualKey.hitBottom);
3707#endif
3708
3709 if (virtualKey.isHit(x, y)) {
3710 return &virtualKey;
3711 }
3712 }
3713
3714 return nullptr;
3715}
3716
3717void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3718 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3719 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3720
3721 current->rawPointerData.clearIdBits();
3722
3723 if (currentPointerCount == 0) {
3724 // No pointers to assign.
3725 return;
3726 }
3727
3728 if (lastPointerCount == 0) {
3729 // All pointers are new.
3730 for (uint32_t i = 0; i < currentPointerCount; i++) {
3731 uint32_t id = i;
3732 current->rawPointerData.pointers[i].id = id;
3733 current->rawPointerData.idToIndex[id] = i;
3734 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3735 }
3736 return;
3737 }
3738
3739 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3740 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3741 // Only one pointer and no change in count so it must have the same id as before.
3742 uint32_t id = last->rawPointerData.pointers[0].id;
3743 current->rawPointerData.pointers[0].id = id;
3744 current->rawPointerData.idToIndex[id] = 0;
3745 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3746 return;
3747 }
3748
3749 // General case.
3750 // We build a heap of squared euclidean distances between current and last pointers
3751 // associated with the current and last pointer indices. Then, we find the best
3752 // match (by distance) for each current pointer.
3753 // The pointers must have the same tool type but it is possible for them to
3754 // transition from hovering to touching or vice-versa while retaining the same id.
3755 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3756
3757 uint32_t heapSize = 0;
3758 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3759 currentPointerIndex++) {
3760 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3761 lastPointerIndex++) {
3762 const RawPointerData::Pointer& currentPointer =
3763 current->rawPointerData.pointers[currentPointerIndex];
3764 const RawPointerData::Pointer& lastPointer =
3765 last->rawPointerData.pointers[lastPointerIndex];
3766 if (currentPointer.toolType == lastPointer.toolType) {
3767 int64_t deltaX = currentPointer.x - lastPointer.x;
3768 int64_t deltaY = currentPointer.y - lastPointer.y;
3769
3770 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3771
3772 // Insert new element into the heap (sift up).
3773 heap[heapSize].currentPointerIndex = currentPointerIndex;
3774 heap[heapSize].lastPointerIndex = lastPointerIndex;
3775 heap[heapSize].distance = distance;
3776 heapSize += 1;
3777 }
3778 }
3779 }
3780
3781 // Heapify
3782 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3783 startIndex -= 1;
3784 for (uint32_t parentIndex = startIndex;;) {
3785 uint32_t childIndex = parentIndex * 2 + 1;
3786 if (childIndex >= heapSize) {
3787 break;
3788 }
3789
3790 if (childIndex + 1 < heapSize &&
3791 heap[childIndex + 1].distance < heap[childIndex].distance) {
3792 childIndex += 1;
3793 }
3794
3795 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3796 break;
3797 }
3798
3799 swap(heap[parentIndex], heap[childIndex]);
3800 parentIndex = childIndex;
3801 }
3802 }
3803
3804#if DEBUG_POINTER_ASSIGNMENT
3805 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3806 for (size_t i = 0; i < heapSize; i++) {
3807 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3808 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3809 }
3810#endif
3811
3812 // Pull matches out by increasing order of distance.
3813 // To avoid reassigning pointers that have already been matched, the loop keeps track
3814 // of which last and current pointers have been matched using the matchedXXXBits variables.
3815 // It also tracks the used pointer id bits.
3816 BitSet32 matchedLastBits(0);
3817 BitSet32 matchedCurrentBits(0);
3818 BitSet32 usedIdBits(0);
3819 bool first = true;
3820 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3821 while (heapSize > 0) {
3822 if (first) {
3823 // The first time through the loop, we just consume the root element of
3824 // the heap (the one with smallest distance).
3825 first = false;
3826 } else {
3827 // Previous iterations consumed the root element of the heap.
3828 // Pop root element off of the heap (sift down).
3829 heap[0] = heap[heapSize];
3830 for (uint32_t parentIndex = 0;;) {
3831 uint32_t childIndex = parentIndex * 2 + 1;
3832 if (childIndex >= heapSize) {
3833 break;
3834 }
3835
3836 if (childIndex + 1 < heapSize &&
3837 heap[childIndex + 1].distance < heap[childIndex].distance) {
3838 childIndex += 1;
3839 }
3840
3841 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3842 break;
3843 }
3844
3845 swap(heap[parentIndex], heap[childIndex]);
3846 parentIndex = childIndex;
3847 }
3848
3849#if DEBUG_POINTER_ASSIGNMENT
3850 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003851 for (size_t j = 0; j < heapSize; j++) {
3852 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3853 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003854 }
3855#endif
3856 }
3857
3858 heapSize -= 1;
3859
3860 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3861 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3862
3863 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3864 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3865
3866 matchedCurrentBits.markBit(currentPointerIndex);
3867 matchedLastBits.markBit(lastPointerIndex);
3868
3869 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3870 current->rawPointerData.pointers[currentPointerIndex].id = id;
3871 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3872 current->rawPointerData.markIdBit(id,
3873 current->rawPointerData.isHovering(
3874 currentPointerIndex));
3875 usedIdBits.markBit(id);
3876
3877#if DEBUG_POINTER_ASSIGNMENT
3878 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3879 ", distance=%" PRIu64,
3880 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3881#endif
3882 break;
3883 }
3884 }
3885
3886 // Assign fresh ids to pointers that were not matched in the process.
3887 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3888 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3889 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3890
3891 current->rawPointerData.pointers[currentPointerIndex].id = id;
3892 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3893 current->rawPointerData.markIdBit(id,
3894 current->rawPointerData.isHovering(currentPointerIndex));
3895
3896#if DEBUG_POINTER_ASSIGNMENT
3897 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3898#endif
3899 }
3900}
3901
3902int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3903 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3904 return AKEY_STATE_VIRTUAL;
3905 }
3906
3907 for (const VirtualKey& virtualKey : mVirtualKeys) {
3908 if (virtualKey.keyCode == keyCode) {
3909 return AKEY_STATE_UP;
3910 }
3911 }
3912
3913 return AKEY_STATE_UNKNOWN;
3914}
3915
3916int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3917 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3918 return AKEY_STATE_VIRTUAL;
3919 }
3920
3921 for (const VirtualKey& virtualKey : mVirtualKeys) {
3922 if (virtualKey.scanCode == scanCode) {
3923 return AKEY_STATE_UP;
3924 }
3925 }
3926
3927 return AKEY_STATE_UNKNOWN;
3928}
3929
3930bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3931 const int32_t* keyCodes, uint8_t* outFlags) {
3932 for (const VirtualKey& virtualKey : mVirtualKeys) {
3933 for (size_t i = 0; i < numCodes; i++) {
3934 if (virtualKey.keyCode == keyCodes[i]) {
3935 outFlags[i] = 1;
3936 }
3937 }
3938 }
3939
3940 return true;
3941}
3942
3943std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3944 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003945 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003946 return std::make_optional(mPointerController->getDisplayId());
3947 } else {
3948 return std::make_optional(mViewport.displayId);
3949 }
3950 }
3951 return std::nullopt;
3952}
3953
3954} // namespace android