blob: b620e2d2144a5c7550cdd8468ed64765f6d61118 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
Chris Yea03dd232020-09-08 19:21:09 -070021#include <input/NamedEnum.h>
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070022#include "TouchInputMapper.h"
23
24#include "CursorButtonAccumulator.h"
25#include "CursorScrollAccumulator.h"
26#include "TouchButtonAccumulator.h"
27#include "TouchCursorInputMapperCommon.h"
28
29namespace android {
30
31// --- Constants ---
32
33// Maximum amount of latency to add to touch events while waiting for data from an
34// external stylus.
35static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
36
37// Maximum amount of time to wait on touch data before pushing out new pressure data.
38static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
39
40// Artificial latency on synthetic events created from stylus data without corresponding touch
41// data.
42static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
43
44// --- Static Definitions ---
45
46template <typename T>
47inline static void swap(T& a, T& b) {
48 T temp = a;
49 a = b;
50 b = temp;
51}
52
53static float calculateCommonVector(float a, float b) {
54 if (a > 0 && b > 0) {
55 return a < b ? a : b;
56 } else if (a < 0 && b < 0) {
57 return a > b ? a : b;
58 } else {
59 return 0;
60 }
61}
62
63inline static float distance(float x1, float y1, float x2, float y2) {
64 return hypotf(x1 - x2, y1 - y2);
65}
66
67inline static int32_t signExtendNybble(int32_t value) {
68 return value >= 8 ? value - 16 : value;
69}
70
71// --- RawPointerAxes ---
72
73RawPointerAxes::RawPointerAxes() {
74 clear();
75}
76
77void RawPointerAxes::clear() {
78 x.clear();
79 y.clear();
80 pressure.clear();
81 touchMajor.clear();
82 touchMinor.clear();
83 toolMajor.clear();
84 toolMinor.clear();
85 orientation.clear();
86 distance.clear();
87 tiltX.clear();
88 tiltY.clear();
89 trackingId.clear();
90 slot.clear();
91}
92
93// --- RawPointerData ---
94
95RawPointerData::RawPointerData() {
96 clear();
97}
98
99void RawPointerData::clear() {
100 pointerCount = 0;
101 clearIdBits();
102}
103
104void RawPointerData::copyFrom(const RawPointerData& other) {
105 pointerCount = other.pointerCount;
106 hoveringIdBits = other.hoveringIdBits;
107 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800108 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109
110 for (uint32_t i = 0; i < pointerCount; i++) {
111 pointers[i] = other.pointers[i];
112
113 int id = pointers[i].id;
114 idToIndex[id] = other.idToIndex[id];
115 }
116}
117
118void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
119 float x = 0, y = 0;
120 uint32_t count = touchingIdBits.count();
121 if (count) {
122 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
123 uint32_t id = idBits.clearFirstMarkedBit();
124 const Pointer& pointer = pointerForId(id);
125 x += pointer.x;
126 y += pointer.y;
127 }
128 x /= count;
129 y /= count;
130 }
131 *outX = x;
132 *outY = y;
133}
134
135// --- CookedPointerData ---
136
137CookedPointerData::CookedPointerData() {
138 clear();
139}
140
141void CookedPointerData::clear() {
142 pointerCount = 0;
143 hoveringIdBits.clear();
144 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800145 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000146 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700147}
148
149void CookedPointerData::copyFrom(const CookedPointerData& other) {
150 pointerCount = other.pointerCount;
151 hoveringIdBits = other.hoveringIdBits;
152 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000153 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700154
155 for (uint32_t i = 0; i < pointerCount; i++) {
156 pointerProperties[i].copyFrom(other.pointerProperties[i]);
157 pointerCoords[i].copyFrom(other.pointerCoords[i]);
158
159 int id = pointerProperties[i].id;
160 idToIndex[id] = other.idToIndex[id];
161 }
162}
163
164// --- TouchInputMapper ---
165
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800166TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
167 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700168 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100169 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800170 mRawSurfaceWidth(-1),
171 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700172 mSurfaceLeft(0),
173 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700174 mSurfaceRight(0),
175 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700176 mPhysicalWidth(-1),
177 mPhysicalHeight(-1),
178 mPhysicalLeft(0),
179 mPhysicalTop(0),
180 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
181
182TouchInputMapper::~TouchInputMapper() {}
183
184uint32_t TouchInputMapper::getSources() {
185 return mSource;
186}
187
188void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
189 InputMapper::populateDeviceInfo(info);
190
Michael Wright227c5542020-07-02 18:30:52 +0100191 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 info->addMotionRange(mOrientedRanges.x);
193 info->addMotionRange(mOrientedRanges.y);
194 info->addMotionRange(mOrientedRanges.pressure);
195
Chris Yef74dc422020-09-02 22:41:50 -0700196 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700197 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
198 //
199 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
200 // motion, i.e. the hardware dimensions, as the finger could move completely across the
201 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700202 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
203 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
204 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
205 x.fuzz, x.resolution);
206 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
207 y.fuzz, y.resolution);
208 }
209
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700210 if (mOrientedRanges.haveSize) {
211 info->addMotionRange(mOrientedRanges.size);
212 }
213
214 if (mOrientedRanges.haveTouchSize) {
215 info->addMotionRange(mOrientedRanges.touchMajor);
216 info->addMotionRange(mOrientedRanges.touchMinor);
217 }
218
219 if (mOrientedRanges.haveToolSize) {
220 info->addMotionRange(mOrientedRanges.toolMajor);
221 info->addMotionRange(mOrientedRanges.toolMinor);
222 }
223
224 if (mOrientedRanges.haveOrientation) {
225 info->addMotionRange(mOrientedRanges.orientation);
226 }
227
228 if (mOrientedRanges.haveDistance) {
229 info->addMotionRange(mOrientedRanges.distance);
230 }
231
232 if (mOrientedRanges.haveTilt) {
233 info->addMotionRange(mOrientedRanges.tilt);
234 }
235
236 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
237 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
238 0.0f);
239 }
240 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
241 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
242 0.0f);
243 }
Michael Wright227c5542020-07-02 18:30:52 +0100244 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700245 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
246 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
247 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
248 x.fuzz, x.resolution);
249 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
250 y.fuzz, y.resolution);
251 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
252 x.fuzz, x.resolution);
253 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
254 y.fuzz, y.resolution);
255 }
256 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
257 }
258}
259
260void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700261 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
262 NamedEnum::string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700263 dumpParameters(dump);
264 dumpVirtualKeys(dump);
265 dumpRawPointerAxes(dump);
266 dumpCalibration(dump);
267 dumpAffineTransformation(dump);
268 dumpSurface(dump);
269
270 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
271 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
272 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
273 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
274 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
275 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
276 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
277 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
278 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
279 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
280 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
281 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
282 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
283 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
284 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
285 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
286 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
287
288 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
289 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
290 mLastRawState.rawPointerData.pointerCount);
291 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
292 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
293 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
294 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
295 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
296 "toolType=%d, isHovering=%s\n",
297 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
298 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
299 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
300 pointer.distance, pointer.toolType, toString(pointer.isHovering));
301 }
302
303 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
304 mLastCookedState.buttonState);
305 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
306 mLastCookedState.cookedPointerData.pointerCount);
307 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
308 const PointerProperties& pointerProperties =
309 mLastCookedState.cookedPointerData.pointerProperties[i];
310 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000311 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
312 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
313 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
315 "toolType=%d, isHovering=%s\n",
316 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
327 pointerProperties.toolType,
328 toString(mLastCookedState.cookedPointerData.isHovering(i)));
329 }
330
331 dump += INDENT3 "Stylus Fusion:\n";
332 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
333 toString(mExternalStylusConnected));
334 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
335 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
336 mExternalStylusFusionTimeout);
337 dump += INDENT3 "External Stylus State:\n";
338 dumpStylusState(dump, mExternalStylusState);
339
Michael Wright227c5542020-07-02 18:30:52 +0100340 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
342 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
343 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
344 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
345 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
346 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
347 }
348}
349
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
351 uint32_t changes) {
352 InputMapper::configure(when, config, changes);
353
354 mConfig = *config;
355
356 if (!changes) { // first time only
357 // Configure basic parameters.
358 configureParameters();
359
360 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mCursorScrollAccumulator.configure(getDeviceContext());
362 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700363
364 // Configure absolute axis information.
365 configureRawPointerAxes();
366
367 // Prepare input device calibration.
368 parseCalibration();
369 resolveCalibration();
370 }
371
372 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
373 // Update location calibration to reflect current settings
374 updateAffineTransformation();
375 }
376
377 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
378 // Update pointer speed.
379 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
380 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
381 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 }
383
384 bool resetNeeded = false;
385 if (!changes ||
386 (changes &
387 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800388 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
390 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
391 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
392 // Configure device sources, surface dimensions, orientation and
393 // scaling factors.
394 configureSurface(when, &resetNeeded);
395 }
396
397 if (changes && resetNeeded) {
398 // Send reset, unless this is the first time the device has been configured,
399 // in which case the reader will call reset itself after all mappers are ready.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800400 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800401 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 }
403}
404
405void TouchInputMapper::resolveExternalStylusPresence() {
406 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800407 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700408 mExternalStylusConnected = !devices.empty();
409
410 if (!mExternalStylusConnected) {
411 resetExternalStylus();
412 }
413}
414
415void TouchInputMapper::configureParameters() {
416 // Use the pointer presentation mode for devices that do not support distinct
417 // multitouch. The spot-based presentation relies on being able to accurately
418 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100420 ? Parameters::GestureMode::SINGLE_TOUCH
421 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422
423 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800424 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
425 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100427 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100429 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700430 } else if (gestureModeString != "default") {
431 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
432 }
433 }
434
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800435 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100437 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800438 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800441 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
442 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 // The device is a cursor device with a touch pad attached.
444 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100445 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446 } else {
447 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100448 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449 }
450
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800451 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452
453 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
455 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100461 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100463 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700464 } else if (deviceTypeString != "default") {
465 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
466 }
467 }
468
Michael Wright227c5542020-07-02 18:30:52 +0100469 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800470 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
471 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472
473 mParameters.hasAssociatedDisplay = false;
474 mParameters.associatedDisplayIsExternal = false;
475 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100476 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
477 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700478 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100479 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800480 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800482 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
483 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
485 }
486 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800487 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488 mParameters.hasAssociatedDisplay = true;
489 }
490
491 // Initial downs on external touch devices should wake the device.
492 // Normally we don't do this for internal touch screens to prevent them from waking
493 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 mParameters.wake = getDeviceContext().isExternal();
495 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496}
497
498void TouchInputMapper::dumpParameters(std::string& dump) {
499 dump += INDENT3 "Parameters:\n";
500
Chris Yea03dd232020-09-08 19:21:09 -0700501 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502
Chris Yea03dd232020-09-08 19:21:09 -0700503 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700504
505 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
506 "displayId='%s'\n",
507 toString(mParameters.hasAssociatedDisplay),
508 toString(mParameters.associatedDisplayIsExternal),
509 mParameters.uniqueDisplayId.c_str());
510 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
511}
512
513void TouchInputMapper::configureRawPointerAxes() {
514 mRawPointerAxes.clear();
515}
516
517void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
518 dump += INDENT3 "Raw Touch Axes:\n";
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
531 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
532}
533
534bool TouchInputMapper::hasExternalStylus() const {
535 return mExternalStylusConnected;
536}
537
538/**
539 * Determine which DisplayViewport to use.
540 * 1. If display port is specified, return the matching viewport. If matching viewport not
541 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800542 * 2. Always use the suggested viewport from WindowManagerService for pointers.
543 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700544 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800545 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700546 */
547std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800548 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800549 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700550 if (displayPort) {
551 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800552 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700553 }
554
Michael Wright227c5542020-07-02 18:30:52 +0100555 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800556 std::optional<DisplayViewport> viewport =
557 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
558 if (viewport) {
559 return viewport;
560 } else {
561 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
562 mConfig.defaultPointerDisplayId);
563 }
564 }
565
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 // Check if uniqueDisplayId is specified in idc file.
567 if (!mParameters.uniqueDisplayId.empty()) {
568 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
569 }
570
571 ViewportType viewportTypeToUse;
572 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100573 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700574 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100575 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700576 }
577
578 std::optional<DisplayViewport> viewport =
579 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100580 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700581 ALOGW("Input device %s should be associated with external display, "
582 "fallback to internal one for the external viewport is not found.",
583 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100584 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700585 }
586
587 return viewport;
588 }
589
590 // No associated display, return a non-display viewport.
591 DisplayViewport newViewport;
592 // Raw width and height in the natural orientation.
593 int32_t rawWidth = mRawPointerAxes.getRawWidth();
594 int32_t rawHeight = mRawPointerAxes.getRawHeight();
595 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
596 return std::make_optional(newViewport);
597}
598
599void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100600 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700601
602 resolveExternalStylusPresence();
603
604 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100605 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800606 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700607 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100608 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700609 if (hasStylus()) {
610 mSource |= AINPUT_SOURCE_STYLUS;
611 }
Michael Wright227c5542020-07-02 18:30:52 +0100612 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700613 mParameters.hasAssociatedDisplay) {
614 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100615 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700616 if (hasStylus()) {
617 mSource |= AINPUT_SOURCE_STYLUS;
618 }
619 if (hasExternalStylus()) {
620 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
621 }
Michael Wright227c5542020-07-02 18:30:52 +0100622 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700623 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100624 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700625 } else {
626 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100627 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700628 }
629
630 // Ensure we have valid X and Y axes.
631 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
632 ALOGW("Touch device '%s' did not report support for X or Y axis! "
633 "The device will be inoperable.",
634 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100635 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700636 return;
637 }
638
639 // Get associated display dimensions.
640 std::optional<DisplayViewport> newViewport = findViewport();
641 if (!newViewport) {
642 ALOGI("Touch device '%s' could not query the properties of its associated "
643 "display. The device will be inoperable until the display size "
644 "becomes available.",
645 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100646 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700647 return;
648 }
649
650 // Raw width and height in the natural orientation.
651 int32_t rawWidth = mRawPointerAxes.getRawWidth();
652 int32_t rawHeight = mRawPointerAxes.getRawHeight();
653
654 bool viewportChanged = mViewport != *newViewport;
655 if (viewportChanged) {
656 mViewport = *newViewport;
657
Michael Wright227c5542020-07-02 18:30:52 +0100658 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700659 // Convert rotated viewport to natural surface coordinates.
660 int32_t naturalLogicalWidth, naturalLogicalHeight;
661 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
662 int32_t naturalPhysicalLeft, naturalPhysicalTop;
663 int32_t naturalDeviceWidth, naturalDeviceHeight;
664 switch (mViewport.orientation) {
665 case DISPLAY_ORIENTATION_90:
666 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
667 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
668 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
669 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800670 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700671 naturalPhysicalTop = mViewport.physicalLeft;
672 naturalDeviceWidth = mViewport.deviceHeight;
673 naturalDeviceHeight = mViewport.deviceWidth;
674 break;
675 case DISPLAY_ORIENTATION_180:
676 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
677 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
678 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
679 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
680 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
681 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
682 naturalDeviceWidth = mViewport.deviceWidth;
683 naturalDeviceHeight = mViewport.deviceHeight;
684 break;
685 case DISPLAY_ORIENTATION_270:
686 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
687 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
688 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
689 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
690 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800691 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700692 naturalDeviceWidth = mViewport.deviceHeight;
693 naturalDeviceHeight = mViewport.deviceWidth;
694 break;
695 case DISPLAY_ORIENTATION_0:
696 default:
697 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
698 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
699 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
700 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
701 naturalPhysicalLeft = mViewport.physicalLeft;
702 naturalPhysicalTop = mViewport.physicalTop;
703 naturalDeviceWidth = mViewport.deviceWidth;
704 naturalDeviceHeight = mViewport.deviceHeight;
705 break;
706 }
707
708 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
709 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
710 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
711 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
712 }
713
714 mPhysicalWidth = naturalPhysicalWidth;
715 mPhysicalHeight = naturalPhysicalHeight;
716 mPhysicalLeft = naturalPhysicalLeft;
717 mPhysicalTop = naturalPhysicalTop;
718
Arthur Hung4197f6b2020-03-16 15:39:59 +0800719 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
720 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700721 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
722 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800723 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
724 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700725
726 mSurfaceOrientation =
727 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
728 } else {
729 mPhysicalWidth = rawWidth;
730 mPhysicalHeight = rawHeight;
731 mPhysicalLeft = 0;
732 mPhysicalTop = 0;
733
Arthur Hung4197f6b2020-03-16 15:39:59 +0800734 mRawSurfaceWidth = rawWidth;
735 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700736 mSurfaceLeft = 0;
737 mSurfaceTop = 0;
738 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
739 }
740 }
741
742 // If moving between pointer modes, need to reset some state.
743 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
744 if (deviceModeChanged) {
745 mOrientedRanges.clear();
746 }
747
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800748 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
749 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100750 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800751 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
752 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800753 if (mPointerController == nullptr) {
754 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700755 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800756 if (mConfig.pointerCapture) {
757 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
758 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700759 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100760 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700761 }
762
763 if (viewportChanged || deviceModeChanged) {
764 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
765 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800766 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700767 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
768
769 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800770 mXScale = float(mRawSurfaceWidth) / rawWidth;
771 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700772 mXTranslate = -mSurfaceLeft;
773 mYTranslate = -mSurfaceTop;
774 mXPrecision = 1.0f / mXScale;
775 mYPrecision = 1.0f / mYScale;
776
777 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
778 mOrientedRanges.x.source = mSource;
779 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
780 mOrientedRanges.y.source = mSource;
781
782 configureVirtualKeys();
783
784 // Scale factor for terms that are not oriented in a particular axis.
785 // If the pixels are square then xScale == yScale otherwise we fake it
786 // by choosing an average.
787 mGeometricScale = avg(mXScale, mYScale);
788
789 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800790 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700791
792 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100793 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700794 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
795 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
796 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
797 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
798 } else {
799 mSizeScale = 0.0f;
800 }
801
802 mOrientedRanges.haveTouchSize = true;
803 mOrientedRanges.haveToolSize = true;
804 mOrientedRanges.haveSize = true;
805
806 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
807 mOrientedRanges.touchMajor.source = mSource;
808 mOrientedRanges.touchMajor.min = 0;
809 mOrientedRanges.touchMajor.max = diagonalSize;
810 mOrientedRanges.touchMajor.flat = 0;
811 mOrientedRanges.touchMajor.fuzz = 0;
812 mOrientedRanges.touchMajor.resolution = 0;
813
814 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
815 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
816
817 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
818 mOrientedRanges.toolMajor.source = mSource;
819 mOrientedRanges.toolMajor.min = 0;
820 mOrientedRanges.toolMajor.max = diagonalSize;
821 mOrientedRanges.toolMajor.flat = 0;
822 mOrientedRanges.toolMajor.fuzz = 0;
823 mOrientedRanges.toolMajor.resolution = 0;
824
825 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
826 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
827
828 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
829 mOrientedRanges.size.source = mSource;
830 mOrientedRanges.size.min = 0;
831 mOrientedRanges.size.max = 1.0;
832 mOrientedRanges.size.flat = 0;
833 mOrientedRanges.size.fuzz = 0;
834 mOrientedRanges.size.resolution = 0;
835 } else {
836 mSizeScale = 0.0f;
837 }
838
839 // Pressure factors.
840 mPressureScale = 0;
841 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100842 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
843 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700844 if (mCalibration.havePressureScale) {
845 mPressureScale = mCalibration.pressureScale;
846 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
847 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
848 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
849 }
850 }
851
852 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
853 mOrientedRanges.pressure.source = mSource;
854 mOrientedRanges.pressure.min = 0;
855 mOrientedRanges.pressure.max = pressureMax;
856 mOrientedRanges.pressure.flat = 0;
857 mOrientedRanges.pressure.fuzz = 0;
858 mOrientedRanges.pressure.resolution = 0;
859
860 // Tilt
861 mTiltXCenter = 0;
862 mTiltXScale = 0;
863 mTiltYCenter = 0;
864 mTiltYScale = 0;
865 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
866 if (mHaveTilt) {
867 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
868 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
869 mTiltXScale = M_PI / 180;
870 mTiltYScale = M_PI / 180;
871
872 mOrientedRanges.haveTilt = true;
873
874 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
875 mOrientedRanges.tilt.source = mSource;
876 mOrientedRanges.tilt.min = 0;
877 mOrientedRanges.tilt.max = M_PI_2;
878 mOrientedRanges.tilt.flat = 0;
879 mOrientedRanges.tilt.fuzz = 0;
880 mOrientedRanges.tilt.resolution = 0;
881 }
882
883 // Orientation
884 mOrientationScale = 0;
885 if (mHaveTilt) {
886 mOrientedRanges.haveOrientation = true;
887
888 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
889 mOrientedRanges.orientation.source = mSource;
890 mOrientedRanges.orientation.min = -M_PI;
891 mOrientedRanges.orientation.max = M_PI;
892 mOrientedRanges.orientation.flat = 0;
893 mOrientedRanges.orientation.fuzz = 0;
894 mOrientedRanges.orientation.resolution = 0;
895 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100896 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700897 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100898 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700899 if (mRawPointerAxes.orientation.valid) {
900 if (mRawPointerAxes.orientation.maxValue > 0) {
901 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
902 } else if (mRawPointerAxes.orientation.minValue < 0) {
903 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
904 } else {
905 mOrientationScale = 0;
906 }
907 }
908 }
909
910 mOrientedRanges.haveOrientation = true;
911
912 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
913 mOrientedRanges.orientation.source = mSource;
914 mOrientedRanges.orientation.min = -M_PI_2;
915 mOrientedRanges.orientation.max = M_PI_2;
916 mOrientedRanges.orientation.flat = 0;
917 mOrientedRanges.orientation.fuzz = 0;
918 mOrientedRanges.orientation.resolution = 0;
919 }
920
921 // Distance
922 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100923 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
924 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925 if (mCalibration.haveDistanceScale) {
926 mDistanceScale = mCalibration.distanceScale;
927 } else {
928 mDistanceScale = 1.0f;
929 }
930 }
931
932 mOrientedRanges.haveDistance = true;
933
934 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
935 mOrientedRanges.distance.source = mSource;
936 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
937 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
938 mOrientedRanges.distance.flat = 0;
939 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
940 mOrientedRanges.distance.resolution = 0;
941 }
942
943 // Compute oriented precision, scales and ranges.
944 // Note that the maximum value reported is an inclusive maximum value so it is one
945 // unit less than the total width or height of surface.
946 switch (mSurfaceOrientation) {
947 case DISPLAY_ORIENTATION_90:
948 case DISPLAY_ORIENTATION_270:
949 mOrientedXPrecision = mYPrecision;
950 mOrientedYPrecision = mXPrecision;
951
952 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800953 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700954 mOrientedRanges.x.flat = 0;
955 mOrientedRanges.x.fuzz = 0;
956 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
957
958 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800959 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700960 mOrientedRanges.y.flat = 0;
961 mOrientedRanges.y.fuzz = 0;
962 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
963 break;
964
965 default:
966 mOrientedXPrecision = mXPrecision;
967 mOrientedYPrecision = mYPrecision;
968
969 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800970 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700971 mOrientedRanges.x.flat = 0;
972 mOrientedRanges.x.fuzz = 0;
973 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
974
975 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800976 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977 mOrientedRanges.y.flat = 0;
978 mOrientedRanges.y.fuzz = 0;
979 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
980 break;
981 }
982
983 // Location
984 updateAffineTransformation();
985
Michael Wright227c5542020-07-02 18:30:52 +0100986 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700987 // Compute pointer gesture detection parameters.
988 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +0800989 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990
991 // Scale movements such that one whole swipe of the touch pad covers a
992 // given area relative to the diagonal size of the display when no acceleration
993 // is applied.
994 // Assume that the touch pad has a square aspect ratio such that movements in
995 // X and Y of the same number of raw units cover the same physical distance.
996 mPointerXMovementScale =
997 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
998 mPointerYMovementScale = mPointerXMovementScale;
999
1000 // Scale zooms to cover a smaller range of the display than movements do.
1001 // This value determines the area around the pointer that is affected by freeform
1002 // pointer gestures.
1003 mPointerXZoomScale =
1004 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1005 mPointerYZoomScale = mPointerXZoomScale;
1006
1007 // Max width between pointers to detect a swipe gesture is more than some fraction
1008 // of the diagonal axis of the touch pad. Touches that are wider than this are
1009 // translated into freeform gestures.
1010 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1011
1012 // Abort current pointer usages because the state has changed.
1013 abortPointerUsage(when, 0 /*policyFlags*/);
1014 }
1015
1016 // Inform the dispatcher about the changes.
1017 *outResetNeeded = true;
1018 bumpGeneration();
1019 }
1020}
1021
1022void TouchInputMapper::dumpSurface(std::string& dump) {
1023 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001024 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1025 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001026 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1027 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001028 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1029 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001030 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1031 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1032 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1033 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1034 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1035}
1036
1037void TouchInputMapper::configureVirtualKeys() {
1038 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001039 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001040
1041 mVirtualKeys.clear();
1042
1043 if (virtualKeyDefinitions.size() == 0) {
1044 return;
1045 }
1046
1047 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1048 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1049 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1050 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1051
1052 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1053 VirtualKey virtualKey;
1054
1055 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1056 int32_t keyCode;
1057 int32_t dummyKeyMetaState;
1058 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001059 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1060 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001061 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1062 continue; // drop the key
1063 }
1064
1065 virtualKey.keyCode = keyCode;
1066 virtualKey.flags = flags;
1067
1068 // convert the key definition's display coordinates into touch coordinates for a hit box
1069 int32_t halfWidth = virtualKeyDefinition.width / 2;
1070 int32_t halfHeight = virtualKeyDefinition.height / 2;
1071
1072 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001073 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001074 touchScreenLeft;
1075 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001076 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001077 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001078 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1079 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001080 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001081 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1082 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001083 touchScreenTop;
1084 mVirtualKeys.push_back(virtualKey);
1085 }
1086}
1087
1088void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1089 if (!mVirtualKeys.empty()) {
1090 dump += INDENT3 "Virtual Keys:\n";
1091
1092 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1093 const VirtualKey& virtualKey = mVirtualKeys[i];
1094 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1095 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1096 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1097 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1098 }
1099 }
1100}
1101
1102void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001103 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104 Calibration& out = mCalibration;
1105
1106 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001107 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001108 String8 sizeCalibrationString;
1109 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1110 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001111 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001113 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001114 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001115 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001117 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001118 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001119 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001120 } else if (sizeCalibrationString != "default") {
1121 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1122 }
1123 }
1124
1125 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1126 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1127 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1128
1129 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001130 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001131 String8 pressureCalibrationString;
1132 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1133 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001134 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 } else if (pressureCalibrationString != "default") {
1140 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1141 pressureCalibrationString.string());
1142 }
1143 }
1144
1145 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1146
1147 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001148 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 String8 orientationCalibrationString;
1150 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1151 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001152 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001153 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001154 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001156 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001157 } else if (orientationCalibrationString != "default") {
1158 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1159 orientationCalibrationString.string());
1160 }
1161 }
1162
1163 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001164 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 String8 distanceCalibrationString;
1166 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1167 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 } else if (distanceCalibrationString != "default") {
1172 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1173 distanceCalibrationString.string());
1174 }
1175 }
1176
1177 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1178
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 String8 coverageCalibrationString;
1181 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1182 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 } else if (coverageCalibrationString != "default") {
1187 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1188 coverageCalibrationString.string());
1189 }
1190 }
1191}
1192
1193void TouchInputMapper::resolveCalibration() {
1194 // Size
1195 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001196 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1197 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 }
1199 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001200 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 }
1202
1203 // Pressure
1204 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001205 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1206 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 }
1208 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001209 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 }
1211
1212 // Orientation
1213 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001214 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1215 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 }
1217 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001218 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 }
1220
1221 // Distance
1222 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001223 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1224 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 }
1226 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001227 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229
1230 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001231 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1232 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 }
1234}
1235
1236void TouchInputMapper::dumpCalibration(std::string& dump) {
1237 dump += INDENT3 "Calibration:\n";
1238
1239 // Size
1240 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001241 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 dump += INDENT4 "touch.size.calibration: none\n";
1243 break;
Michael Wright227c5542020-07-02 18:30:52 +01001244 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 dump += INDENT4 "touch.size.calibration: geometric\n";
1246 break;
Michael Wright227c5542020-07-02 18:30:52 +01001247 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 dump += INDENT4 "touch.size.calibration: diameter\n";
1249 break;
Michael Wright227c5542020-07-02 18:30:52 +01001250 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 dump += INDENT4 "touch.size.calibration: box\n";
1252 break;
Michael Wright227c5542020-07-02 18:30:52 +01001253 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 dump += INDENT4 "touch.size.calibration: area\n";
1255 break;
1256 default:
1257 ALOG_ASSERT(false);
1258 }
1259
1260 if (mCalibration.haveSizeScale) {
1261 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1262 }
1263
1264 if (mCalibration.haveSizeBias) {
1265 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1266 }
1267
1268 if (mCalibration.haveSizeIsSummed) {
1269 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1270 toString(mCalibration.sizeIsSummed));
1271 }
1272
1273 // Pressure
1274 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001275 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 dump += INDENT4 "touch.pressure.calibration: none\n";
1277 break;
Michael Wright227c5542020-07-02 18:30:52 +01001278 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 dump += INDENT4 "touch.pressure.calibration: physical\n";
1280 break;
Michael Wright227c5542020-07-02 18:30:52 +01001281 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1283 break;
1284 default:
1285 ALOG_ASSERT(false);
1286 }
1287
1288 if (mCalibration.havePressureScale) {
1289 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1290 }
1291
1292 // Orientation
1293 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001294 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 dump += INDENT4 "touch.orientation.calibration: none\n";
1296 break;
Michael Wright227c5542020-07-02 18:30:52 +01001297 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1299 break;
Michael Wright227c5542020-07-02 18:30:52 +01001300 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += INDENT4 "touch.orientation.calibration: vector\n";
1302 break;
1303 default:
1304 ALOG_ASSERT(false);
1305 }
1306
1307 // Distance
1308 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.distance.calibration: none\n";
1311 break;
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.distance.calibration: scaled\n";
1314 break;
1315 default:
1316 ALOG_ASSERT(false);
1317 }
1318
1319 if (mCalibration.haveDistanceScale) {
1320 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1321 }
1322
1323 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001324 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.coverage.calibration: none\n";
1326 break;
Michael Wright227c5542020-07-02 18:30:52 +01001327 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.coverage.calibration: box\n";
1329 break;
1330 default:
1331 ALOG_ASSERT(false);
1332 }
1333}
1334
1335void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1336 dump += INDENT3 "Affine Transformation:\n";
1337
1338 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1339 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1340 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1341 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1342 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1343 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1344}
1345
1346void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001347 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001348 mSurfaceOrientation);
1349}
1350
1351void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001352 mCursorButtonAccumulator.reset(getDeviceContext());
1353 mCursorScrollAccumulator.reset(getDeviceContext());
1354 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001355
1356 mPointerVelocityControl.reset();
1357 mWheelXVelocityControl.reset();
1358 mWheelYVelocityControl.reset();
1359
1360 mRawStatesPending.clear();
1361 mCurrentRawState.clear();
1362 mCurrentCookedState.clear();
1363 mLastRawState.clear();
1364 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001365 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366 mSentHoverEnter = false;
1367 mHavePointerIds = false;
1368 mCurrentMotionAborted = false;
1369 mDownTime = 0;
1370
1371 mCurrentVirtualKey.down = false;
1372
1373 mPointerGesture.reset();
1374 mPointerSimple.reset();
1375 resetExternalStylus();
1376
1377 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001378 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379 mPointerController->clearSpots();
1380 }
1381
1382 InputMapper::reset(when);
1383}
1384
1385void TouchInputMapper::resetExternalStylus() {
1386 mExternalStylusState.clear();
1387 mExternalStylusId = -1;
1388 mExternalStylusFusionTimeout = LLONG_MAX;
1389 mExternalStylusDataPending = false;
1390}
1391
1392void TouchInputMapper::clearStylusDataPendingFlags() {
1393 mExternalStylusDataPending = false;
1394 mExternalStylusFusionTimeout = LLONG_MAX;
1395}
1396
1397void TouchInputMapper::process(const RawEvent* rawEvent) {
1398 mCursorButtonAccumulator.process(rawEvent);
1399 mCursorScrollAccumulator.process(rawEvent);
1400 mTouchButtonAccumulator.process(rawEvent);
1401
1402 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1403 sync(rawEvent->when);
1404 }
1405}
1406
1407void TouchInputMapper::sync(nsecs_t when) {
1408 const RawState* last =
1409 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1410
1411 // Push a new state.
1412 mRawStatesPending.emplace_back();
1413
1414 RawState* next = &mRawStatesPending.back();
1415 next->clear();
1416 next->when = when;
1417
1418 // Sync button state.
1419 next->buttonState =
1420 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1421
1422 // Sync scroll
1423 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1424 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1425 mCursorScrollAccumulator.finishSync();
1426
1427 // Sync touch
1428 syncTouch(when, next);
1429
1430 // Assign pointer ids.
1431 if (!mHavePointerIds) {
1432 assignPointerIds(last, next);
1433 }
1434
1435#if DEBUG_RAW_EVENTS
1436 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001437 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1439 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001440 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1441 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001442#endif
1443
1444 processRawTouches(false /*timeout*/);
1445}
1446
1447void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001448 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001449 // Drop all input if the device is disabled.
1450 mCurrentRawState.clear();
1451 mRawStatesPending.clear();
1452 return;
1453 }
1454
1455 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1456 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1457 // touching the current state will only observe the events that have been dispatched to the
1458 // rest of the pipeline.
1459 const size_t N = mRawStatesPending.size();
1460 size_t count;
1461 for (count = 0; count < N; count++) {
1462 const RawState& next = mRawStatesPending[count];
1463
1464 // A failure to assign the stylus id means that we're waiting on stylus data
1465 // and so should defer the rest of the pipeline.
1466 if (assignExternalStylusId(next, timeout)) {
1467 break;
1468 }
1469
1470 // All ready to go.
1471 clearStylusDataPendingFlags();
1472 mCurrentRawState.copyFrom(next);
1473 if (mCurrentRawState.when < mLastRawState.when) {
1474 mCurrentRawState.when = mLastRawState.when;
1475 }
1476 cookAndDispatch(mCurrentRawState.when);
1477 }
1478 if (count != 0) {
1479 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1480 }
1481
1482 if (mExternalStylusDataPending) {
1483 if (timeout) {
1484 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1485 clearStylusDataPendingFlags();
1486 mCurrentRawState.copyFrom(mLastRawState);
1487#if DEBUG_STYLUS_FUSION
1488 ALOGD("Timeout expired, synthesizing event with new stylus data");
1489#endif
1490 cookAndDispatch(when);
1491 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1492 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1493 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1494 }
1495 }
1496}
1497
1498void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1499 // Always start with a clean state.
1500 mCurrentCookedState.clear();
1501
1502 // Apply stylus buttons to current raw state.
1503 applyExternalStylusButtonState(when);
1504
1505 // Handle policy on initial down or hover events.
1506 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1507 mCurrentRawState.rawPointerData.pointerCount != 0;
1508
1509 uint32_t policyFlags = 0;
1510 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1511 if (initialDown || buttonsPressed) {
1512 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001513 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001514 getContext()->fadePointer();
1515 }
1516
1517 if (mParameters.wake) {
1518 policyFlags |= POLICY_FLAG_WAKE;
1519 }
1520 }
1521
1522 // Consume raw off-screen touches before cooking pointer data.
1523 // If touches are consumed, subsequent code will not receive any pointer data.
1524 if (consumeRawTouches(when, policyFlags)) {
1525 mCurrentRawState.rawPointerData.clear();
1526 }
1527
1528 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1529 // with cooked pointer data that has the same ids and indices as the raw data.
1530 // The following code can use either the raw or cooked data, as needed.
1531 cookPointerData();
1532
1533 // Apply stylus pressure to current cooked state.
1534 applyExternalStylusTouchState(when);
1535
1536 // Synthesize key down from raw buttons if needed.
1537 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1538 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1539 mCurrentCookedState.buttonState);
1540
1541 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001542 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001543 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1544 uint32_t id = idBits.clearFirstMarkedBit();
1545 const RawPointerData::Pointer& pointer =
1546 mCurrentRawState.rawPointerData.pointerForId(id);
1547 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1548 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1549 mCurrentCookedState.stylusIdBits.markBit(id);
1550 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1551 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1552 mCurrentCookedState.fingerIdBits.markBit(id);
1553 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1554 mCurrentCookedState.mouseIdBits.markBit(id);
1555 }
1556 }
1557 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1558 uint32_t id = idBits.clearFirstMarkedBit();
1559 const RawPointerData::Pointer& pointer =
1560 mCurrentRawState.rawPointerData.pointerForId(id);
1561 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1562 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1563 mCurrentCookedState.stylusIdBits.markBit(id);
1564 }
1565 }
1566
1567 // Stylus takes precedence over all tools, then mouse, then finger.
1568 PointerUsage pointerUsage = mPointerUsage;
1569 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1570 mCurrentCookedState.mouseIdBits.clear();
1571 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001572 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001573 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1574 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001575 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1577 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001578 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 }
1580
1581 dispatchPointerUsage(when, policyFlags, pointerUsage);
1582 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001583 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001584 mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001585 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1586 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001587
1588 mPointerController->setButtonState(mCurrentRawState.buttonState);
1589 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1590 mCurrentCookedState.cookedPointerData.idToIndex,
1591 mCurrentCookedState.cookedPointerData.touchingIdBits,
1592 mViewport.displayId);
1593 }
1594
1595 if (!mCurrentMotionAborted) {
1596 dispatchButtonRelease(when, policyFlags);
1597 dispatchHoverExit(when, policyFlags);
1598 dispatchTouches(when, policyFlags);
1599 dispatchHoverEnterAndMove(when, policyFlags);
1600 dispatchButtonPress(when, policyFlags);
1601 }
1602
1603 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1604 mCurrentMotionAborted = false;
1605 }
1606 }
1607
1608 // Synthesize key up from raw buttons if needed.
1609 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1610 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1611 mCurrentCookedState.buttonState);
1612
1613 // Clear some transient state.
1614 mCurrentRawState.rawVScroll = 0;
1615 mCurrentRawState.rawHScroll = 0;
1616
1617 // Copy current touch to last touch in preparation for the next cycle.
1618 mLastRawState.copyFrom(mCurrentRawState);
1619 mLastCookedState.copyFrom(mCurrentCookedState);
1620}
1621
1622void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001623 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1625 }
1626}
1627
1628void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1629 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1630 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1631
1632 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1633 float pressure = mExternalStylusState.pressure;
1634 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1635 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1636 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1637 }
1638 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1639 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1640
1641 PointerProperties& properties =
1642 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1643 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1644 properties.toolType = mExternalStylusState.toolType;
1645 }
1646 }
1647}
1648
1649bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001650 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001651 return false;
1652 }
1653
1654 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1655 state.rawPointerData.pointerCount != 0;
1656 if (initialDown) {
1657 if (mExternalStylusState.pressure != 0.0f) {
1658#if DEBUG_STYLUS_FUSION
1659 ALOGD("Have both stylus and touch data, beginning fusion");
1660#endif
1661 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1662 } else if (timeout) {
1663#if DEBUG_STYLUS_FUSION
1664 ALOGD("Timeout expired, assuming touch is not a stylus.");
1665#endif
1666 resetExternalStylus();
1667 } else {
1668 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1669 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1670 }
1671#if DEBUG_STYLUS_FUSION
1672 ALOGD("No stylus data but stylus is connected, requesting timeout "
1673 "(%" PRId64 "ms)",
1674 mExternalStylusFusionTimeout);
1675#endif
1676 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1677 return true;
1678 }
1679 }
1680
1681 // Check if the stylus pointer has gone up.
1682 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1683#if DEBUG_STYLUS_FUSION
1684 ALOGD("Stylus pointer is going up");
1685#endif
1686 mExternalStylusId = -1;
1687 }
1688
1689 return false;
1690}
1691
1692void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001693 if (mDeviceMode == DeviceMode::POINTER) {
1694 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001695 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1696 }
Michael Wright227c5542020-07-02 18:30:52 +01001697 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001698 if (mExternalStylusFusionTimeout < when) {
1699 processRawTouches(true /*timeout*/);
1700 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1701 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1702 }
1703 }
1704}
1705
1706void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1707 mExternalStylusState.copyFrom(state);
1708 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1709 // We're either in the middle of a fused stream of data or we're waiting on data before
1710 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1711 // data.
1712 mExternalStylusDataPending = true;
1713 processRawTouches(false /*timeout*/);
1714 }
1715}
1716
1717bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1718 // Check for release of a virtual key.
1719 if (mCurrentVirtualKey.down) {
1720 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1721 // Pointer went up while virtual key was down.
1722 mCurrentVirtualKey.down = false;
1723 if (!mCurrentVirtualKey.ignored) {
1724#if DEBUG_VIRTUAL_KEYS
1725 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1726 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1727#endif
1728 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1729 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1730 }
1731 return true;
1732 }
1733
1734 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1735 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1736 const RawPointerData::Pointer& pointer =
1737 mCurrentRawState.rawPointerData.pointerForId(id);
1738 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1739 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1740 // Pointer is still within the space of the virtual key.
1741 return true;
1742 }
1743 }
1744
1745 // Pointer left virtual key area or another pointer also went down.
1746 // Send key cancellation but do not consume the touch yet.
1747 // This is useful when the user swipes through from the virtual key area
1748 // into the main display surface.
1749 mCurrentVirtualKey.down = false;
1750 if (!mCurrentVirtualKey.ignored) {
1751#if DEBUG_VIRTUAL_KEYS
1752 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1753 mCurrentVirtualKey.scanCode);
1754#endif
1755 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1756 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1757 AKEY_EVENT_FLAG_CANCELED);
1758 }
1759 }
1760
1761 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1762 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1763 // Pointer just went down. Check for virtual key press or off-screen touches.
1764 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1765 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001766 // Exclude unscaled device for inside surface checking.
1767 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001768 // If exactly one pointer went down, check for virtual key hit.
1769 // Otherwise we will drop the entire stroke.
1770 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1771 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1772 if (virtualKey) {
1773 mCurrentVirtualKey.down = true;
1774 mCurrentVirtualKey.downTime = when;
1775 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1776 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1777 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001778 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1779 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780
1781 if (!mCurrentVirtualKey.ignored) {
1782#if DEBUG_VIRTUAL_KEYS
1783 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1784 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1785#endif
1786 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1787 AKEY_EVENT_FLAG_FROM_SYSTEM |
1788 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1789 }
1790 }
1791 }
1792 return true;
1793 }
1794 }
1795
1796 // Disable all virtual key touches that happen within a short time interval of the
1797 // most recent touch within the screen area. The idea is to filter out stray
1798 // virtual key presses when interacting with the touch screen.
1799 //
1800 // Problems we're trying to solve:
1801 //
1802 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1803 // virtual key area that is implemented by a separate touch panel and accidentally
1804 // triggers a virtual key.
1805 //
1806 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1807 // area and accidentally triggers a virtual key. This often happens when virtual keys
1808 // are layed out below the screen near to where the on screen keyboard's space bar
1809 // is displayed.
1810 if (mConfig.virtualKeyQuietTime > 0 &&
1811 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001812 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001813 }
1814 return false;
1815}
1816
1817void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1818 int32_t keyEventAction, int32_t keyEventFlags) {
1819 int32_t keyCode = mCurrentVirtualKey.keyCode;
1820 int32_t scanCode = mCurrentVirtualKey.scanCode;
1821 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001822 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001823 policyFlags |= POLICY_FLAG_VIRTUAL;
1824
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001825 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1826 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1827 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001828 getListener()->notifyKey(&args);
1829}
1830
1831void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1832 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1833 if (!currentIdBits.isEmpty()) {
1834 int32_t metaState = getContext()->getGlobalMetaState();
1835 int32_t buttonState = mCurrentCookedState.buttonState;
1836 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1837 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1838 mCurrentCookedState.cookedPointerData.pointerProperties,
1839 mCurrentCookedState.cookedPointerData.pointerCoords,
1840 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1841 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1842 mCurrentMotionAborted = true;
1843 }
1844}
1845
1846void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1847 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1848 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1849 int32_t metaState = getContext()->getGlobalMetaState();
1850 int32_t buttonState = mCurrentCookedState.buttonState;
1851
1852 if (currentIdBits == lastIdBits) {
1853 if (!currentIdBits.isEmpty()) {
1854 // No pointer id changes so this is a move event.
1855 // The listener takes care of batching moves so we don't have to deal with that here.
1856 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1857 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1858 mCurrentCookedState.cookedPointerData.pointerProperties,
1859 mCurrentCookedState.cookedPointerData.pointerCoords,
1860 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1861 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1862 }
1863 } else {
1864 // There may be pointers going up and pointers going down and pointers moving
1865 // all at the same time.
1866 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1867 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1868 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1869 BitSet32 dispatchedIdBits(lastIdBits.value);
1870
1871 // Update last coordinates of pointers that have moved so that we observe the new
1872 // pointer positions at the same time as other pointers that have just gone up.
1873 bool moveNeeded =
1874 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1875 mCurrentCookedState.cookedPointerData.pointerCoords,
1876 mCurrentCookedState.cookedPointerData.idToIndex,
1877 mLastCookedState.cookedPointerData.pointerProperties,
1878 mLastCookedState.cookedPointerData.pointerCoords,
1879 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1880 if (buttonState != mLastCookedState.buttonState) {
1881 moveNeeded = true;
1882 }
1883
1884 // Dispatch pointer up events.
1885 while (!upIdBits.isEmpty()) {
1886 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001887 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1888 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1889 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001890 mLastCookedState.cookedPointerData.pointerProperties,
1891 mLastCookedState.cookedPointerData.pointerCoords,
1892 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1893 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1894 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001895 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001896 }
1897
1898 // Dispatch move events if any of the remaining pointers moved from their old locations.
1899 // Although applications receive new locations as part of individual pointer up
1900 // events, they do not generally handle them except when presented in a move event.
1901 if (moveNeeded && !moveIdBits.isEmpty()) {
1902 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1903 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1904 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1905 mCurrentCookedState.cookedPointerData.pointerCoords,
1906 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1907 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1908 }
1909
1910 // Dispatch pointer down events using the new pointer locations.
1911 while (!downIdBits.isEmpty()) {
1912 uint32_t downId = downIdBits.clearFirstMarkedBit();
1913 dispatchedIdBits.markBit(downId);
1914
1915 if (dispatchedIdBits.count() == 1) {
1916 // First pointer is going down. Set down time.
1917 mDownTime = when;
1918 }
1919
1920 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1921 metaState, buttonState, 0,
1922 mCurrentCookedState.cookedPointerData.pointerProperties,
1923 mCurrentCookedState.cookedPointerData.pointerCoords,
1924 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1925 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1926 }
1927 }
1928}
1929
1930void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1931 if (mSentHoverEnter &&
1932 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1933 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1934 int32_t metaState = getContext()->getGlobalMetaState();
1935 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1936 mLastCookedState.buttonState, 0,
1937 mLastCookedState.cookedPointerData.pointerProperties,
1938 mLastCookedState.cookedPointerData.pointerCoords,
1939 mLastCookedState.cookedPointerData.idToIndex,
1940 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1941 mOrientedYPrecision, mDownTime);
1942 mSentHoverEnter = false;
1943 }
1944}
1945
1946void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1947 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1948 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1949 int32_t metaState = getContext()->getGlobalMetaState();
1950 if (!mSentHoverEnter) {
1951 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1952 metaState, mCurrentRawState.buttonState, 0,
1953 mCurrentCookedState.cookedPointerData.pointerProperties,
1954 mCurrentCookedState.cookedPointerData.pointerCoords,
1955 mCurrentCookedState.cookedPointerData.idToIndex,
1956 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1957 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1958 mSentHoverEnter = true;
1959 }
1960
1961 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1962 mCurrentRawState.buttonState, 0,
1963 mCurrentCookedState.cookedPointerData.pointerProperties,
1964 mCurrentCookedState.cookedPointerData.pointerCoords,
1965 mCurrentCookedState.cookedPointerData.idToIndex,
1966 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1967 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1968 }
1969}
1970
1971void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1972 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1973 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1974 const int32_t metaState = getContext()->getGlobalMetaState();
1975 int32_t buttonState = mLastCookedState.buttonState;
1976 while (!releasedButtons.isEmpty()) {
1977 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
1978 buttonState &= ~actionButton;
1979 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1980 actionButton, 0, metaState, buttonState, 0,
1981 mCurrentCookedState.cookedPointerData.pointerProperties,
1982 mCurrentCookedState.cookedPointerData.pointerCoords,
1983 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
1984 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1985 }
1986}
1987
1988void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
1989 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
1990 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
1991 const int32_t metaState = getContext()->getGlobalMetaState();
1992 int32_t buttonState = mLastCookedState.buttonState;
1993 while (!pressedButtons.isEmpty()) {
1994 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
1995 buttonState |= actionButton;
1996 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
1997 0, metaState, buttonState, 0,
1998 mCurrentCookedState.cookedPointerData.pointerProperties,
1999 mCurrentCookedState.cookedPointerData.pointerCoords,
2000 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2001 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2002 }
2003}
2004
2005const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2006 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2007 return cookedPointerData.touchingIdBits;
2008 }
2009 return cookedPointerData.hoveringIdBits;
2010}
2011
2012void TouchInputMapper::cookPointerData() {
2013 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2014
2015 mCurrentCookedState.cookedPointerData.clear();
2016 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2017 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2018 mCurrentRawState.rawPointerData.hoveringIdBits;
2019 mCurrentCookedState.cookedPointerData.touchingIdBits =
2020 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002021 mCurrentCookedState.cookedPointerData.canceledIdBits =
2022 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002023
2024 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2025 mCurrentCookedState.buttonState = 0;
2026 } else {
2027 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2028 }
2029
2030 // Walk through the the active pointers and map device coordinates onto
2031 // surface coordinates and adjust for display orientation.
2032 for (uint32_t i = 0; i < currentPointerCount; i++) {
2033 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2034
2035 // Size
2036 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2037 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002038 case Calibration::SizeCalibration::GEOMETRIC:
2039 case Calibration::SizeCalibration::DIAMETER:
2040 case Calibration::SizeCalibration::BOX:
2041 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002042 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2043 touchMajor = in.touchMajor;
2044 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2045 toolMajor = in.toolMajor;
2046 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2047 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2048 : in.touchMajor;
2049 } else if (mRawPointerAxes.touchMajor.valid) {
2050 toolMajor = touchMajor = in.touchMajor;
2051 toolMinor = touchMinor =
2052 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2053 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2054 : in.touchMajor;
2055 } else if (mRawPointerAxes.toolMajor.valid) {
2056 touchMajor = toolMajor = in.toolMajor;
2057 touchMinor = toolMinor =
2058 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2059 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2060 : in.toolMajor;
2061 } else {
2062 ALOG_ASSERT(false,
2063 "No touch or tool axes. "
2064 "Size calibration should have been resolved to NONE.");
2065 touchMajor = 0;
2066 touchMinor = 0;
2067 toolMajor = 0;
2068 toolMinor = 0;
2069 size = 0;
2070 }
2071
2072 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2073 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2074 if (touchingCount > 1) {
2075 touchMajor /= touchingCount;
2076 touchMinor /= touchingCount;
2077 toolMajor /= touchingCount;
2078 toolMinor /= touchingCount;
2079 size /= touchingCount;
2080 }
2081 }
2082
Michael Wright227c5542020-07-02 18:30:52 +01002083 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002084 touchMajor *= mGeometricScale;
2085 touchMinor *= mGeometricScale;
2086 toolMajor *= mGeometricScale;
2087 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002088 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2090 touchMinor = touchMajor;
2091 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2092 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002093 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002094 touchMinor = touchMajor;
2095 toolMinor = toolMajor;
2096 }
2097
2098 mCalibration.applySizeScaleAndBias(&touchMajor);
2099 mCalibration.applySizeScaleAndBias(&touchMinor);
2100 mCalibration.applySizeScaleAndBias(&toolMajor);
2101 mCalibration.applySizeScaleAndBias(&toolMinor);
2102 size *= mSizeScale;
2103 break;
2104 default:
2105 touchMajor = 0;
2106 touchMinor = 0;
2107 toolMajor = 0;
2108 toolMinor = 0;
2109 size = 0;
2110 break;
2111 }
2112
2113 // Pressure
2114 float pressure;
2115 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002116 case Calibration::PressureCalibration::PHYSICAL:
2117 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002118 pressure = in.pressure * mPressureScale;
2119 break;
2120 default:
2121 pressure = in.isHovering ? 0 : 1;
2122 break;
2123 }
2124
2125 // Tilt and Orientation
2126 float tilt;
2127 float orientation;
2128 if (mHaveTilt) {
2129 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2130 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2131 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2132 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2133 } else {
2134 tilt = 0;
2135
2136 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002137 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002138 orientation = in.orientation * mOrientationScale;
2139 break;
Michael Wright227c5542020-07-02 18:30:52 +01002140 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2142 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2143 if (c1 != 0 || c2 != 0) {
2144 orientation = atan2f(c1, c2) * 0.5f;
2145 float confidence = hypotf(c1, c2);
2146 float scale = 1.0f + confidence / 16.0f;
2147 touchMajor *= scale;
2148 touchMinor /= scale;
2149 toolMajor *= scale;
2150 toolMinor /= scale;
2151 } else {
2152 orientation = 0;
2153 }
2154 break;
2155 }
2156 default:
2157 orientation = 0;
2158 }
2159 }
2160
2161 // Distance
2162 float distance;
2163 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002164 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165 distance = in.distance * mDistanceScale;
2166 break;
2167 default:
2168 distance = 0;
2169 }
2170
2171 // Coverage
2172 int32_t rawLeft, rawTop, rawRight, rawBottom;
2173 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002174 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002175 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2176 rawRight = in.toolMinor & 0x0000ffff;
2177 rawBottom = in.toolMajor & 0x0000ffff;
2178 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2179 break;
2180 default:
2181 rawLeft = rawTop = rawRight = rawBottom = 0;
2182 break;
2183 }
2184
2185 // Adjust X,Y coords for device calibration
2186 // TODO: Adjust coverage coords?
2187 float xTransformed = in.x, yTransformed = in.y;
2188 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002189 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002190
2191 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002192 float left, top, right, bottom;
2193
2194 switch (mSurfaceOrientation) {
2195 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002196 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2197 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2198 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2199 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2200 orientation -= M_PI_2;
2201 if (mOrientedRanges.haveOrientation &&
2202 orientation < mOrientedRanges.orientation.min) {
2203 orientation +=
2204 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2205 }
2206 break;
2207 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002208 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2209 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2210 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2211 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2212 orientation -= M_PI;
2213 if (mOrientedRanges.haveOrientation &&
2214 orientation < mOrientedRanges.orientation.min) {
2215 orientation +=
2216 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2217 }
2218 break;
2219 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002220 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2221 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2222 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2223 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2224 orientation += M_PI_2;
2225 if (mOrientedRanges.haveOrientation &&
2226 orientation > mOrientedRanges.orientation.max) {
2227 orientation -=
2228 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2229 }
2230 break;
2231 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002232 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2233 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2234 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2235 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2236 break;
2237 }
2238
2239 // Write output coords.
2240 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2241 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002242 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2243 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2245 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2246 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2247 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2248 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2249 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2250 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002251 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002252 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2253 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2254 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2255 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2256 } else {
2257 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2258 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2259 }
2260
Chris Ye364fdb52020-08-05 15:07:56 -07002261 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002262 uint32_t id = in.id;
2263 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2264 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2265 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2266 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2267 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2268 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2269 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2270 }
2271
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002272 // Write output properties.
2273 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002274 properties.clear();
2275 properties.id = id;
2276 properties.toolType = in.toolType;
2277
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002278 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002279 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002280 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002281 }
2282}
2283
2284void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2285 PointerUsage pointerUsage) {
2286 if (pointerUsage != mPointerUsage) {
2287 abortPointerUsage(when, policyFlags);
2288 mPointerUsage = pointerUsage;
2289 }
2290
2291 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002292 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002293 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2294 break;
Michael Wright227c5542020-07-02 18:30:52 +01002295 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 dispatchPointerStylus(when, policyFlags);
2297 break;
Michael Wright227c5542020-07-02 18:30:52 +01002298 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002299 dispatchPointerMouse(when, policyFlags);
2300 break;
Michael Wright227c5542020-07-02 18:30:52 +01002301 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002302 break;
2303 }
2304}
2305
2306void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2307 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002308 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002309 abortPointerGestures(when, policyFlags);
2310 break;
Michael Wright227c5542020-07-02 18:30:52 +01002311 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002312 abortPointerStylus(when, policyFlags);
2313 break;
Michael Wright227c5542020-07-02 18:30:52 +01002314 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 abortPointerMouse(when, policyFlags);
2316 break;
Michael Wright227c5542020-07-02 18:30:52 +01002317 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002318 break;
2319 }
2320
Michael Wright227c5542020-07-02 18:30:52 +01002321 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002322}
2323
2324void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2325 // Update current gesture coordinates.
2326 bool cancelPreviousGesture, finishPreviousGesture;
2327 bool sendEvents =
2328 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2329 if (!sendEvents) {
2330 return;
2331 }
2332 if (finishPreviousGesture) {
2333 cancelPreviousGesture = false;
2334 }
2335
2336 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002337 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002338 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339 if (finishPreviousGesture || cancelPreviousGesture) {
2340 mPointerController->clearSpots();
2341 }
2342
Michael Wright227c5542020-07-02 18:30:52 +01002343 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2345 mPointerGesture.currentGestureIdToIndex,
2346 mPointerGesture.currentGestureIdBits,
2347 mPointerController->getDisplayId());
2348 }
2349 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002350 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 }
2352
2353 // Show or hide the pointer if needed.
2354 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002355 case PointerGesture::Mode::NEUTRAL:
2356 case PointerGesture::Mode::QUIET:
2357 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2358 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002360 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 }
2362 break;
Michael Wright227c5542020-07-02 18:30:52 +01002363 case PointerGesture::Mode::TAP:
2364 case PointerGesture::Mode::TAP_DRAG:
2365 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2366 case PointerGesture::Mode::HOVER:
2367 case PointerGesture::Mode::PRESS:
2368 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 // Unfade the pointer when the current gesture manipulates the
2370 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002371 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 break;
Michael Wright227c5542020-07-02 18:30:52 +01002373 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 // Fade the pointer when the current gesture manipulates a different
2375 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002376 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002377 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002379 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 }
2381 break;
2382 }
2383
2384 // Send events!
2385 int32_t metaState = getContext()->getGlobalMetaState();
2386 int32_t buttonState = mCurrentCookedState.buttonState;
2387
2388 // Update last coordinates of pointers that have moved so that we observe the new
2389 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002390 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2391 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2392 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2393 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2394 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2395 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 bool moveNeeded = false;
2397 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2398 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2399 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2400 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2401 mPointerGesture.lastGestureIdBits.value);
2402 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2403 mPointerGesture.currentGestureCoords,
2404 mPointerGesture.currentGestureIdToIndex,
2405 mPointerGesture.lastGestureProperties,
2406 mPointerGesture.lastGestureCoords,
2407 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2408 if (buttonState != mLastCookedState.buttonState) {
2409 moveNeeded = true;
2410 }
2411 }
2412
2413 // Send motion events for all pointers that went up or were canceled.
2414 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2415 if (!dispatchedGestureIdBits.isEmpty()) {
2416 if (cancelPreviousGesture) {
2417 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2418 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2419 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2420 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2421 mPointerGesture.downTime);
2422
2423 dispatchedGestureIdBits.clear();
2424 } else {
2425 BitSet32 upGestureIdBits;
2426 if (finishPreviousGesture) {
2427 upGestureIdBits = dispatchedGestureIdBits;
2428 } else {
2429 upGestureIdBits.value =
2430 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2431 }
2432 while (!upGestureIdBits.isEmpty()) {
2433 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2434
2435 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2436 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2437 mPointerGesture.lastGestureProperties,
2438 mPointerGesture.lastGestureCoords,
2439 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2440 0, mPointerGesture.downTime);
2441
2442 dispatchedGestureIdBits.clearBit(id);
2443 }
2444 }
2445 }
2446
2447 // Send motion events for all pointers that moved.
2448 if (moveNeeded) {
2449 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2450 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2451 mPointerGesture.currentGestureProperties,
2452 mPointerGesture.currentGestureCoords,
2453 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2454 mPointerGesture.downTime);
2455 }
2456
2457 // Send motion events for all pointers that went down.
2458 if (down) {
2459 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2460 ~dispatchedGestureIdBits.value);
2461 while (!downGestureIdBits.isEmpty()) {
2462 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2463 dispatchedGestureIdBits.markBit(id);
2464
2465 if (dispatchedGestureIdBits.count() == 1) {
2466 mPointerGesture.downTime = when;
2467 }
2468
2469 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2470 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2471 mPointerGesture.currentGestureCoords,
2472 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2473 0, mPointerGesture.downTime);
2474 }
2475 }
2476
2477 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002478 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2480 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2481 mPointerGesture.currentGestureProperties,
2482 mPointerGesture.currentGestureCoords,
2483 mPointerGesture.currentGestureIdToIndex,
2484 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2485 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2486 // Synthesize a hover move event after all pointers go up to indicate that
2487 // the pointer is hovering again even if the user is not currently touching
2488 // the touch pad. This ensures that a view will receive a fresh hover enter
2489 // event after a tap.
2490 float x, y;
2491 mPointerController->getPosition(&x, &y);
2492
2493 PointerProperties pointerProperties;
2494 pointerProperties.clear();
2495 pointerProperties.id = 0;
2496 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2497
2498 PointerCoords pointerCoords;
2499 pointerCoords.clear();
2500 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2501 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2502
2503 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002504 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2505 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2506 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2507 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2508 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 getListener()->notifyMotion(&args);
2510 }
2511
2512 // Update state.
2513 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2514 if (!down) {
2515 mPointerGesture.lastGestureIdBits.clear();
2516 } else {
2517 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2518 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2519 uint32_t id = idBits.clearFirstMarkedBit();
2520 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2521 mPointerGesture.lastGestureProperties[index].copyFrom(
2522 mPointerGesture.currentGestureProperties[index]);
2523 mPointerGesture.lastGestureCoords[index].copyFrom(
2524 mPointerGesture.currentGestureCoords[index]);
2525 mPointerGesture.lastGestureIdToIndex[id] = index;
2526 }
2527 }
2528}
2529
2530void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2531 // Cancel previously dispatches pointers.
2532 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2533 int32_t metaState = getContext()->getGlobalMetaState();
2534 int32_t buttonState = mCurrentRawState.buttonState;
2535 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2536 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2537 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2538 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2539 0, 0, mPointerGesture.downTime);
2540 }
2541
2542 // Reset the current pointer gesture.
2543 mPointerGesture.reset();
2544 mPointerVelocityControl.reset();
2545
2546 // Remove any current spots.
2547 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002548 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002549 mPointerController->clearSpots();
2550 }
2551}
2552
2553bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2554 bool* outFinishPreviousGesture, bool isTimeout) {
2555 *outCancelPreviousGesture = false;
2556 *outFinishPreviousGesture = false;
2557
2558 // Handle TAP timeout.
2559 if (isTimeout) {
2560#if DEBUG_GESTURES
2561 ALOGD("Gestures: Processing timeout");
2562#endif
2563
Michael Wright227c5542020-07-02 18:30:52 +01002564 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002565 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2566 // The tap/drag timeout has not yet expired.
2567 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2568 mConfig.pointerGestureTapDragInterval);
2569 } else {
2570 // The tap is finished.
2571#if DEBUG_GESTURES
2572 ALOGD("Gestures: TAP finished");
2573#endif
2574 *outFinishPreviousGesture = true;
2575
2576 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002577 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002578 mPointerGesture.currentGestureIdBits.clear();
2579
2580 mPointerVelocityControl.reset();
2581 return true;
2582 }
2583 }
2584
2585 // We did not handle this timeout.
2586 return false;
2587 }
2588
2589 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2590 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2591
2592 // Update the velocity tracker.
2593 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002594 std::vector<VelocityTracker::Position> positions;
2595 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002596 uint32_t id = idBits.clearFirstMarkedBit();
2597 const RawPointerData::Pointer& pointer =
2598 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002599 float x = pointer.x * mPointerXMovementScale;
2600 float y = pointer.y * mPointerYMovementScale;
2601 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002602 }
2603 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2604 positions);
2605 }
2606
2607 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2608 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002609 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2610 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2611 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002612 mPointerGesture.resetTap();
2613 }
2614
2615 // Pick a new active touch id if needed.
2616 // Choose an arbitrary pointer that just went down, if there is one.
2617 // Otherwise choose an arbitrary remaining pointer.
2618 // This guarantees we always have an active touch id when there is at least one pointer.
2619 // We keep the same active touch id for as long as possible.
2620 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2621 int32_t activeTouchId = lastActiveTouchId;
2622 if (activeTouchId < 0) {
2623 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2624 activeTouchId = mPointerGesture.activeTouchId =
2625 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2626 mPointerGesture.firstTouchTime = when;
2627 }
2628 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2629 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2630 activeTouchId = mPointerGesture.activeTouchId =
2631 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2632 } else {
2633 activeTouchId = mPointerGesture.activeTouchId = -1;
2634 }
2635 }
2636
2637 // Determine whether we are in quiet time.
2638 bool isQuietTime = false;
2639 if (activeTouchId < 0) {
2640 mPointerGesture.resetQuietTime();
2641 } else {
2642 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2643 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002644 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2645 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2646 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002647 currentFingerCount < 2) {
2648 // Enter quiet time when exiting swipe or freeform state.
2649 // This is to prevent accidentally entering the hover state and flinging the
2650 // pointer when finishing a swipe and there is still one pointer left onscreen.
2651 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002652 } else if (mPointerGesture.lastGestureMode ==
2653 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002654 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2655 // Enter quiet time when releasing the button and there are still two or more
2656 // fingers down. This may indicate that one finger was used to press the button
2657 // but it has not gone up yet.
2658 isQuietTime = true;
2659 }
2660 if (isQuietTime) {
2661 mPointerGesture.quietTime = when;
2662 }
2663 }
2664 }
2665
2666 // Switch states based on button and pointer state.
2667 if (isQuietTime) {
2668 // Case 1: Quiet time. (QUIET)
2669#if DEBUG_GESTURES
2670 ALOGD("Gestures: QUIET for next %0.3fms",
2671 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2672#endif
Michael Wright227c5542020-07-02 18:30:52 +01002673 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002674 *outFinishPreviousGesture = true;
2675 }
2676
2677 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002678 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002679 mPointerGesture.currentGestureIdBits.clear();
2680
2681 mPointerVelocityControl.reset();
2682 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2683 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2684 // The pointer follows the active touch point.
2685 // Emit DOWN, MOVE, UP events at the pointer location.
2686 //
2687 // Only the active touch matters; other fingers are ignored. This policy helps
2688 // to handle the case where the user places a second finger on the touch pad
2689 // to apply the necessary force to depress an integrated button below the surface.
2690 // We don't want the second finger to be delivered to applications.
2691 //
2692 // For this to work well, we need to make sure to track the pointer that is really
2693 // active. If the user first puts one finger down to click then adds another
2694 // finger to drag then the active pointer should switch to the finger that is
2695 // being dragged.
2696#if DEBUG_GESTURES
2697 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2698 "currentFingerCount=%d",
2699 activeTouchId, currentFingerCount);
2700#endif
2701 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002702 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002703 *outFinishPreviousGesture = true;
2704 mPointerGesture.activeGestureId = 0;
2705 }
2706
2707 // Switch pointers if needed.
2708 // Find the fastest pointer and follow it.
2709 if (activeTouchId >= 0 && currentFingerCount > 1) {
2710 int32_t bestId = -1;
2711 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2712 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2713 uint32_t id = idBits.clearFirstMarkedBit();
2714 float vx, vy;
2715 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2716 float speed = hypotf(vx, vy);
2717 if (speed > bestSpeed) {
2718 bestId = id;
2719 bestSpeed = speed;
2720 }
2721 }
2722 }
2723 if (bestId >= 0 && bestId != activeTouchId) {
2724 mPointerGesture.activeTouchId = activeTouchId = bestId;
2725#if DEBUG_GESTURES
2726 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2727 "bestId=%d, bestSpeed=%0.3f",
2728 bestId, bestSpeed);
2729#endif
2730 }
2731 }
2732
2733 float deltaX = 0, deltaY = 0;
2734 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2735 const RawPointerData::Pointer& currentPointer =
2736 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2737 const RawPointerData::Pointer& lastPointer =
2738 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2739 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2740 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2741
2742 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2743 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2744
2745 // Move the pointer using a relative motion.
2746 // When using spots, the click will occur at the position of the anchor
2747 // spot and all other spots will move there.
2748 mPointerController->move(deltaX, deltaY);
2749 } else {
2750 mPointerVelocityControl.reset();
2751 }
2752
2753 float x, y;
2754 mPointerController->getPosition(&x, &y);
2755
Michael Wright227c5542020-07-02 18:30:52 +01002756 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002757 mPointerGesture.currentGestureIdBits.clear();
2758 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2759 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2760 mPointerGesture.currentGestureProperties[0].clear();
2761 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2762 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2763 mPointerGesture.currentGestureCoords[0].clear();
2764 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2765 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2766 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2767 } else if (currentFingerCount == 0) {
2768 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002769 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002770 *outFinishPreviousGesture = true;
2771 }
2772
2773 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2774 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2775 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002776 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2777 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002778 lastFingerCount == 1) {
2779 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2780 float x, y;
2781 mPointerController->getPosition(&x, &y);
2782 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2783 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2784#if DEBUG_GESTURES
2785 ALOGD("Gestures: TAP");
2786#endif
2787
2788 mPointerGesture.tapUpTime = when;
2789 getContext()->requestTimeoutAtTime(when +
2790 mConfig.pointerGestureTapDragInterval);
2791
2792 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002793 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 mPointerGesture.currentGestureIdBits.clear();
2795 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2796 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2797 mPointerGesture.currentGestureProperties[0].clear();
2798 mPointerGesture.currentGestureProperties[0].id =
2799 mPointerGesture.activeGestureId;
2800 mPointerGesture.currentGestureProperties[0].toolType =
2801 AMOTION_EVENT_TOOL_TYPE_FINGER;
2802 mPointerGesture.currentGestureCoords[0].clear();
2803 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2804 mPointerGesture.tapX);
2805 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2806 mPointerGesture.tapY);
2807 mPointerGesture.currentGestureCoords[0]
2808 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2809
2810 tapped = true;
2811 } else {
2812#if DEBUG_GESTURES
2813 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2814 y - mPointerGesture.tapY);
2815#endif
2816 }
2817 } else {
2818#if DEBUG_GESTURES
2819 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2820 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2821 (when - mPointerGesture.tapDownTime) * 0.000001f);
2822 } else {
2823 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2824 }
2825#endif
2826 }
2827 }
2828
2829 mPointerVelocityControl.reset();
2830
2831 if (!tapped) {
2832#if DEBUG_GESTURES
2833 ALOGD("Gestures: NEUTRAL");
2834#endif
2835 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002836 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002837 mPointerGesture.currentGestureIdBits.clear();
2838 }
2839 } else if (currentFingerCount == 1) {
2840 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2841 // The pointer follows the active touch point.
2842 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2843 // When in TAP_DRAG, emit MOVE events at the pointer location.
2844 ALOG_ASSERT(activeTouchId >= 0);
2845
Michael Wright227c5542020-07-02 18:30:52 +01002846 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2847 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002848 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2849 float x, y;
2850 mPointerController->getPosition(&x, &y);
2851 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2852 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002853 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 } else {
2855#if DEBUG_GESTURES
2856 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2857 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2858#endif
2859 }
2860 } else {
2861#if DEBUG_GESTURES
2862 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2863 (when - mPointerGesture.tapUpTime) * 0.000001f);
2864#endif
2865 }
Michael Wright227c5542020-07-02 18:30:52 +01002866 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2867 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002868 }
2869
2870 float deltaX = 0, deltaY = 0;
2871 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2872 const RawPointerData::Pointer& currentPointer =
2873 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2874 const RawPointerData::Pointer& lastPointer =
2875 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2876 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2877 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2878
2879 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2880 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2881
2882 // Move the pointer using a relative motion.
2883 // When using spots, the hover or drag will occur at the position of the anchor spot.
2884 mPointerController->move(deltaX, deltaY);
2885 } else {
2886 mPointerVelocityControl.reset();
2887 }
2888
2889 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002890 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891#if DEBUG_GESTURES
2892 ALOGD("Gestures: TAP_DRAG");
2893#endif
2894 down = true;
2895 } else {
2896#if DEBUG_GESTURES
2897 ALOGD("Gestures: HOVER");
2898#endif
Michael Wright227c5542020-07-02 18:30:52 +01002899 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002900 *outFinishPreviousGesture = true;
2901 }
2902 mPointerGesture.activeGestureId = 0;
2903 down = false;
2904 }
2905
2906 float x, y;
2907 mPointerController->getPosition(&x, &y);
2908
2909 mPointerGesture.currentGestureIdBits.clear();
2910 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2911 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2912 mPointerGesture.currentGestureProperties[0].clear();
2913 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2914 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2915 mPointerGesture.currentGestureCoords[0].clear();
2916 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2917 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2918 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2919 down ? 1.0f : 0.0f);
2920
2921 if (lastFingerCount == 0 && currentFingerCount != 0) {
2922 mPointerGesture.resetTap();
2923 mPointerGesture.tapDownTime = when;
2924 mPointerGesture.tapX = x;
2925 mPointerGesture.tapY = y;
2926 }
2927 } else {
2928 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2929 // We need to provide feedback for each finger that goes down so we cannot wait
2930 // for the fingers to move before deciding what to do.
2931 //
2932 // The ambiguous case is deciding what to do when there are two fingers down but they
2933 // have not moved enough to determine whether they are part of a drag or part of a
2934 // freeform gesture, or just a press or long-press at the pointer location.
2935 //
2936 // When there are two fingers we start with the PRESS hypothesis and we generate a
2937 // down at the pointer location.
2938 //
2939 // When the two fingers move enough or when additional fingers are added, we make
2940 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2941 ALOG_ASSERT(activeTouchId >= 0);
2942
2943 bool settled = when >=
2944 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002945 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2946 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2947 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002948 *outFinishPreviousGesture = true;
2949 } else if (!settled && currentFingerCount > lastFingerCount) {
2950 // Additional pointers have gone down but not yet settled.
2951 // Reset the gesture.
2952#if DEBUG_GESTURES
2953 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2954 "settle time remaining %0.3fms",
2955 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2956 when) * 0.000001f);
2957#endif
2958 *outCancelPreviousGesture = true;
2959 } else {
2960 // Continue previous gesture.
2961 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2962 }
2963
2964 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002965 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002966 mPointerGesture.activeGestureId = 0;
2967 mPointerGesture.referenceIdBits.clear();
2968 mPointerVelocityControl.reset();
2969
2970 // Use the centroid and pointer location as the reference points for the gesture.
2971#if DEBUG_GESTURES
2972 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2973 "settle time remaining %0.3fms",
2974 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2975 when) * 0.000001f);
2976#endif
2977 mCurrentRawState.rawPointerData
2978 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
2979 &mPointerGesture.referenceTouchY);
2980 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
2981 &mPointerGesture.referenceGestureY);
2982 }
2983
2984 // Clear the reference deltas for fingers not yet included in the reference calculation.
2985 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
2986 ~mPointerGesture.referenceIdBits.value);
2987 !idBits.isEmpty();) {
2988 uint32_t id = idBits.clearFirstMarkedBit();
2989 mPointerGesture.referenceDeltas[id].dx = 0;
2990 mPointerGesture.referenceDeltas[id].dy = 0;
2991 }
2992 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
2993
2994 // Add delta for all fingers and calculate a common movement delta.
2995 float commonDeltaX = 0, commonDeltaY = 0;
2996 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
2997 mCurrentCookedState.fingerIdBits.value);
2998 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
2999 bool first = (idBits == commonIdBits);
3000 uint32_t id = idBits.clearFirstMarkedBit();
3001 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3002 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3003 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3004 delta.dx += cpd.x - lpd.x;
3005 delta.dy += cpd.y - lpd.y;
3006
3007 if (first) {
3008 commonDeltaX = delta.dx;
3009 commonDeltaY = delta.dy;
3010 } else {
3011 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3012 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3013 }
3014 }
3015
3016 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003017 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003018 float dist[MAX_POINTER_ID + 1];
3019 int32_t distOverThreshold = 0;
3020 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3021 uint32_t id = idBits.clearFirstMarkedBit();
3022 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3023 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3024 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3025 distOverThreshold += 1;
3026 }
3027 }
3028
3029 // Only transition when at least two pointers have moved further than
3030 // the minimum distance threshold.
3031 if (distOverThreshold >= 2) {
3032 if (currentFingerCount > 2) {
3033 // There are more than two pointers, switch to FREEFORM.
3034#if DEBUG_GESTURES
3035 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3036 currentFingerCount);
3037#endif
3038 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003039 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003040 } else {
3041 // There are exactly two pointers.
3042 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3043 uint32_t id1 = idBits.clearFirstMarkedBit();
3044 uint32_t id2 = idBits.firstMarkedBit();
3045 const RawPointerData::Pointer& p1 =
3046 mCurrentRawState.rawPointerData.pointerForId(id1);
3047 const RawPointerData::Pointer& p2 =
3048 mCurrentRawState.rawPointerData.pointerForId(id2);
3049 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3050 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3051 // There are two pointers but they are too far apart for a SWIPE,
3052 // switch to FREEFORM.
3053#if DEBUG_GESTURES
3054 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3055 mutualDistance, mPointerGestureMaxSwipeWidth);
3056#endif
3057 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003058 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003059 } else {
3060 // There are two pointers. Wait for both pointers to start moving
3061 // before deciding whether this is a SWIPE or FREEFORM gesture.
3062 float dist1 = dist[id1];
3063 float dist2 = dist[id2];
3064 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3065 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3066 // Calculate the dot product of the displacement vectors.
3067 // When the vectors are oriented in approximately the same direction,
3068 // the angle betweeen them is near zero and the cosine of the angle
3069 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3070 // mag(v2).
3071 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3072 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3073 float dx1 = delta1.dx * mPointerXZoomScale;
3074 float dy1 = delta1.dy * mPointerYZoomScale;
3075 float dx2 = delta2.dx * mPointerXZoomScale;
3076 float dy2 = delta2.dy * mPointerYZoomScale;
3077 float dot = dx1 * dx2 + dy1 * dy2;
3078 float cosine = dot / (dist1 * dist2); // denominator always > 0
3079 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3080 // Pointers are moving in the same direction. Switch to SWIPE.
3081#if DEBUG_GESTURES
3082 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3083 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3084 "cosine %0.3f >= %0.3f",
3085 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3086 mConfig.pointerGestureMultitouchMinDistance, cosine,
3087 mConfig.pointerGestureSwipeTransitionAngleCosine);
3088#endif
Michael Wright227c5542020-07-02 18:30:52 +01003089 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003090 } else {
3091 // Pointers are moving in different directions. Switch to FREEFORM.
3092#if DEBUG_GESTURES
3093 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3094 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3095 "cosine %0.3f < %0.3f",
3096 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3097 mConfig.pointerGestureMultitouchMinDistance, cosine,
3098 mConfig.pointerGestureSwipeTransitionAngleCosine);
3099#endif
3100 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003101 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003102 }
3103 }
3104 }
3105 }
3106 }
Michael Wright227c5542020-07-02 18:30:52 +01003107 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003108 // Switch from SWIPE to FREEFORM if additional pointers go down.
3109 // Cancel previous gesture.
3110 if (currentFingerCount > 2) {
3111#if DEBUG_GESTURES
3112 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3113 currentFingerCount);
3114#endif
3115 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003116 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003117 }
3118 }
3119
3120 // Move the reference points based on the overall group motion of the fingers
3121 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003122 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003123 (commonDeltaX || commonDeltaY)) {
3124 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3125 uint32_t id = idBits.clearFirstMarkedBit();
3126 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3127 delta.dx = 0;
3128 delta.dy = 0;
3129 }
3130
3131 mPointerGesture.referenceTouchX += commonDeltaX;
3132 mPointerGesture.referenceTouchY += commonDeltaY;
3133
3134 commonDeltaX *= mPointerXMovementScale;
3135 commonDeltaY *= mPointerYMovementScale;
3136
3137 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3138 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3139
3140 mPointerGesture.referenceGestureX += commonDeltaX;
3141 mPointerGesture.referenceGestureY += commonDeltaY;
3142 }
3143
3144 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003145 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3146 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003147 // PRESS or SWIPE mode.
3148#if DEBUG_GESTURES
3149 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3150 "activeGestureId=%d, currentTouchPointerCount=%d",
3151 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3152#endif
3153 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3154
3155 mPointerGesture.currentGestureIdBits.clear();
3156 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3157 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3158 mPointerGesture.currentGestureProperties[0].clear();
3159 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3160 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3161 mPointerGesture.currentGestureCoords[0].clear();
3162 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3163 mPointerGesture.referenceGestureX);
3164 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3165 mPointerGesture.referenceGestureY);
3166 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003167 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003168 // FREEFORM mode.
3169#if DEBUG_GESTURES
3170 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3171 "activeGestureId=%d, currentTouchPointerCount=%d",
3172 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3173#endif
3174 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3175
3176 mPointerGesture.currentGestureIdBits.clear();
3177
3178 BitSet32 mappedTouchIdBits;
3179 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003180 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003181 // Initially, assign the active gesture id to the active touch point
3182 // if there is one. No other touch id bits are mapped yet.
3183 if (!*outCancelPreviousGesture) {
3184 mappedTouchIdBits.markBit(activeTouchId);
3185 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3186 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3187 mPointerGesture.activeGestureId;
3188 } else {
3189 mPointerGesture.activeGestureId = -1;
3190 }
3191 } else {
3192 // Otherwise, assume we mapped all touches from the previous frame.
3193 // Reuse all mappings that are still applicable.
3194 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3195 mCurrentCookedState.fingerIdBits.value;
3196 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3197
3198 // Check whether we need to choose a new active gesture id because the
3199 // current went went up.
3200 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3201 ~mCurrentCookedState.fingerIdBits.value);
3202 !upTouchIdBits.isEmpty();) {
3203 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3204 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3205 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3206 mPointerGesture.activeGestureId = -1;
3207 break;
3208 }
3209 }
3210 }
3211
3212#if DEBUG_GESTURES
3213 ALOGD("Gestures: FREEFORM follow up "
3214 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3215 "activeGestureId=%d",
3216 mappedTouchIdBits.value, usedGestureIdBits.value,
3217 mPointerGesture.activeGestureId);
3218#endif
3219
3220 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3221 for (uint32_t i = 0; i < currentFingerCount; i++) {
3222 uint32_t touchId = idBits.clearFirstMarkedBit();
3223 uint32_t gestureId;
3224 if (!mappedTouchIdBits.hasBit(touchId)) {
3225 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3226 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3227#if DEBUG_GESTURES
3228 ALOGD("Gestures: FREEFORM "
3229 "new mapping for touch id %d -> gesture id %d",
3230 touchId, gestureId);
3231#endif
3232 } else {
3233 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3234#if DEBUG_GESTURES
3235 ALOGD("Gestures: FREEFORM "
3236 "existing mapping for touch id %d -> gesture id %d",
3237 touchId, gestureId);
3238#endif
3239 }
3240 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3241 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3242
3243 const RawPointerData::Pointer& pointer =
3244 mCurrentRawState.rawPointerData.pointerForId(touchId);
3245 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3246 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3247 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3248
3249 mPointerGesture.currentGestureProperties[i].clear();
3250 mPointerGesture.currentGestureProperties[i].id = gestureId;
3251 mPointerGesture.currentGestureProperties[i].toolType =
3252 AMOTION_EVENT_TOOL_TYPE_FINGER;
3253 mPointerGesture.currentGestureCoords[i].clear();
3254 mPointerGesture.currentGestureCoords[i]
3255 .setAxisValue(AMOTION_EVENT_AXIS_X,
3256 mPointerGesture.referenceGestureX + deltaX);
3257 mPointerGesture.currentGestureCoords[i]
3258 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3259 mPointerGesture.referenceGestureY + deltaY);
3260 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3261 1.0f);
3262 }
3263
3264 if (mPointerGesture.activeGestureId < 0) {
3265 mPointerGesture.activeGestureId =
3266 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3267#if DEBUG_GESTURES
3268 ALOGD("Gestures: FREEFORM new "
3269 "activeGestureId=%d",
3270 mPointerGesture.activeGestureId);
3271#endif
3272 }
3273 }
3274 }
3275
3276 mPointerController->setButtonState(mCurrentRawState.buttonState);
3277
3278#if DEBUG_GESTURES
3279 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3280 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3281 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3282 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3283 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3284 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3285 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3286 uint32_t id = idBits.clearFirstMarkedBit();
3287 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3288 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3289 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3290 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3291 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3292 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3293 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3294 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3295 }
3296 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3297 uint32_t id = idBits.clearFirstMarkedBit();
3298 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3299 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3300 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3301 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3302 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3303 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3304 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3305 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3306 }
3307#endif
3308 return true;
3309}
3310
3311void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3312 mPointerSimple.currentCoords.clear();
3313 mPointerSimple.currentProperties.clear();
3314
3315 bool down, hovering;
3316 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3317 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3318 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3319 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3320 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3321 mPointerController->setPosition(x, y);
3322
3323 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3324 down = !hovering;
3325
3326 mPointerController->getPosition(&x, &y);
3327 mPointerSimple.currentCoords.copyFrom(
3328 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3329 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3330 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3331 mPointerSimple.currentProperties.id = 0;
3332 mPointerSimple.currentProperties.toolType =
3333 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3334 } else {
3335 down = false;
3336 hovering = false;
3337 }
3338
3339 dispatchPointerSimple(when, policyFlags, down, hovering);
3340}
3341
3342void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3343 abortPointerSimple(when, policyFlags);
3344}
3345
3346void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3347 mPointerSimple.currentCoords.clear();
3348 mPointerSimple.currentProperties.clear();
3349
3350 bool down, hovering;
3351 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3352 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3353 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3354 float deltaX = 0, deltaY = 0;
3355 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3356 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3357 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3358 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3359 mPointerXMovementScale;
3360 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3361 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3362 mPointerYMovementScale;
3363
3364 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3365 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3366
3367 mPointerController->move(deltaX, deltaY);
3368 } else {
3369 mPointerVelocityControl.reset();
3370 }
3371
3372 down = isPointerDown(mCurrentRawState.buttonState);
3373 hovering = !down;
3374
3375 float x, y;
3376 mPointerController->getPosition(&x, &y);
3377 mPointerSimple.currentCoords.copyFrom(
3378 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3379 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3380 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3381 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3382 hovering ? 0.0f : 1.0f);
3383 mPointerSimple.currentProperties.id = 0;
3384 mPointerSimple.currentProperties.toolType =
3385 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3386 } else {
3387 mPointerVelocityControl.reset();
3388
3389 down = false;
3390 hovering = false;
3391 }
3392
3393 dispatchPointerSimple(when, policyFlags, down, hovering);
3394}
3395
3396void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3397 abortPointerSimple(when, policyFlags);
3398
3399 mPointerVelocityControl.reset();
3400}
3401
3402void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3403 bool hovering) {
3404 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003405
3406 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003407 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003408 mPointerController->clearSpots();
3409 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003410 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003411 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003412 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003413 }
Garfield Tan9514d782020-11-10 16:37:23 -08003414 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003415
3416 float xCursorPosition;
3417 float yCursorPosition;
3418 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3419
3420 if (mPointerSimple.down && !down) {
3421 mPointerSimple.down = false;
3422
3423 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003424 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3425 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003426 mLastRawState.buttonState, MotionClassification::NONE,
3427 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3428 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3429 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3430 /* videoFrames */ {});
3431 getListener()->notifyMotion(&args);
3432 }
3433
3434 if (mPointerSimple.hovering && !hovering) {
3435 mPointerSimple.hovering = false;
3436
3437 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003438 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3439 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3440 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003441 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3442 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3443 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3444 /* videoFrames */ {});
3445 getListener()->notifyMotion(&args);
3446 }
3447
3448 if (down) {
3449 if (!mPointerSimple.down) {
3450 mPointerSimple.down = true;
3451 mPointerSimple.downTime = when;
3452
3453 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003454 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003455 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3456 metaState, mCurrentRawState.buttonState,
3457 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3458 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3459 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3460 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3461 getListener()->notifyMotion(&args);
3462 }
3463
3464 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003465 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3466 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003467 mCurrentRawState.buttonState, MotionClassification::NONE,
3468 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3469 &mPointerSimple.currentCoords, mOrientedXPrecision,
3470 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3471 mPointerSimple.downTime, /* videoFrames */ {});
3472 getListener()->notifyMotion(&args);
3473 }
3474
3475 if (hovering) {
3476 if (!mPointerSimple.hovering) {
3477 mPointerSimple.hovering = true;
3478
3479 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003480 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003481 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3482 metaState, mCurrentRawState.buttonState,
3483 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3484 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3485 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3486 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3487 getListener()->notifyMotion(&args);
3488 }
3489
3490 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003491 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3492 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3493 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003494 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3495 &mPointerSimple.currentCoords, mOrientedXPrecision,
3496 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3497 mPointerSimple.downTime, /* videoFrames */ {});
3498 getListener()->notifyMotion(&args);
3499 }
3500
3501 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3502 float vscroll = mCurrentRawState.rawVScroll;
3503 float hscroll = mCurrentRawState.rawHScroll;
3504 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3505 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3506
3507 // Send scroll.
3508 PointerCoords pointerCoords;
3509 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3510 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3511 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3512
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003513 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3514 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515 mCurrentRawState.buttonState, MotionClassification::NONE,
3516 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3517 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3518 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3519 /* videoFrames */ {});
3520 getListener()->notifyMotion(&args);
3521 }
3522
3523 // Save state.
3524 if (down || hovering) {
3525 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3526 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3527 } else {
3528 mPointerSimple.reset();
3529 }
3530}
3531
3532void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3533 mPointerSimple.currentCoords.clear();
3534 mPointerSimple.currentProperties.clear();
3535
3536 dispatchPointerSimple(when, policyFlags, false, false);
3537}
3538
3539void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3540 int32_t action, int32_t actionButton, int32_t flags,
3541 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3542 const PointerProperties* properties,
3543 const PointerCoords* coords, const uint32_t* idToIndex,
3544 BitSet32 idBits, int32_t changedId, float xPrecision,
3545 float yPrecision, nsecs_t downTime) {
3546 PointerCoords pointerCoords[MAX_POINTERS];
3547 PointerProperties pointerProperties[MAX_POINTERS];
3548 uint32_t pointerCount = 0;
3549 while (!idBits.isEmpty()) {
3550 uint32_t id = idBits.clearFirstMarkedBit();
3551 uint32_t index = idToIndex[id];
3552 pointerProperties[pointerCount].copyFrom(properties[index]);
3553 pointerCoords[pointerCount].copyFrom(coords[index]);
3554
3555 if (changedId >= 0 && id == uint32_t(changedId)) {
3556 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3557 }
3558
3559 pointerCount += 1;
3560 }
3561
3562 ALOG_ASSERT(pointerCount != 0);
3563
3564 if (changedId >= 0 && pointerCount == 1) {
3565 // Replace initial down and final up action.
3566 // We can compare the action without masking off the changed pointer index
3567 // because we know the index is 0.
3568 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3569 action = AMOTION_EVENT_ACTION_DOWN;
3570 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003571 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3572 action = AMOTION_EVENT_ACTION_CANCEL;
3573 } else {
3574 action = AMOTION_EVENT_ACTION_UP;
3575 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003576 } else {
3577 // Can't happen.
3578 ALOG_ASSERT(false);
3579 }
3580 }
3581 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3582 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003583 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003584 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3585 }
3586 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3587 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003588 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589 std::for_each(frames.begin(), frames.end(),
3590 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003591 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3592 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3594 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3595 downTime, std::move(frames));
3596 getListener()->notifyMotion(&args);
3597}
3598
3599bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3600 const PointerCoords* inCoords,
3601 const uint32_t* inIdToIndex,
3602 PointerProperties* outProperties,
3603 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3604 BitSet32 idBits) const {
3605 bool changed = false;
3606 while (!idBits.isEmpty()) {
3607 uint32_t id = idBits.clearFirstMarkedBit();
3608 uint32_t inIndex = inIdToIndex[id];
3609 uint32_t outIndex = outIdToIndex[id];
3610
3611 const PointerProperties& curInProperties = inProperties[inIndex];
3612 const PointerCoords& curInCoords = inCoords[inIndex];
3613 PointerProperties& curOutProperties = outProperties[outIndex];
3614 PointerCoords& curOutCoords = outCoords[outIndex];
3615
3616 if (curInProperties != curOutProperties) {
3617 curOutProperties.copyFrom(curInProperties);
3618 changed = true;
3619 }
3620
3621 if (curInCoords != curOutCoords) {
3622 curOutCoords.copyFrom(curInCoords);
3623 changed = true;
3624 }
3625 }
3626 return changed;
3627}
3628
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629void TouchInputMapper::cancelTouch(nsecs_t when) {
3630 abortPointerUsage(when, 0 /*policyFlags*/);
3631 abortTouches(when, 0 /* policyFlags*/);
3632}
3633
Arthur Hung4197f6b2020-03-16 15:39:59 +08003634// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003635void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003636 // Scale to surface coordinate.
3637 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3638 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3639
3640 // Rotate to surface coordinate.
3641 // 0 - no swap and reverse.
3642 // 90 - swap x/y and reverse y.
3643 // 180 - reverse x, y.
3644 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003645 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003646 case DISPLAY_ORIENTATION_0:
3647 x = xScaled + mXTranslate;
3648 y = yScaled + mYTranslate;
3649 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003650 case DISPLAY_ORIENTATION_90:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003651 y = mSurfaceRight - xScaled;
3652 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003653 break;
3654 case DISPLAY_ORIENTATION_180:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003655 x = mSurfaceRight - xScaled;
3656 y = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003657 break;
3658 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003659 y = xScaled + mXTranslate;
3660 x = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003661 break;
3662 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003663 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003664 }
3665}
3666
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003667bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003668 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3669 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3670
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003671 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003672 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003673 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003674 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003675}
3676
3677const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3678 for (const VirtualKey& virtualKey : mVirtualKeys) {
3679#if DEBUG_VIRTUAL_KEYS
3680 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3681 "left=%d, top=%d, right=%d, bottom=%d",
3682 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3683 virtualKey.hitRight, virtualKey.hitBottom);
3684#endif
3685
3686 if (virtualKey.isHit(x, y)) {
3687 return &virtualKey;
3688 }
3689 }
3690
3691 return nullptr;
3692}
3693
3694void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3695 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3696 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3697
3698 current->rawPointerData.clearIdBits();
3699
3700 if (currentPointerCount == 0) {
3701 // No pointers to assign.
3702 return;
3703 }
3704
3705 if (lastPointerCount == 0) {
3706 // All pointers are new.
3707 for (uint32_t i = 0; i < currentPointerCount; i++) {
3708 uint32_t id = i;
3709 current->rawPointerData.pointers[i].id = id;
3710 current->rawPointerData.idToIndex[id] = i;
3711 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3712 }
3713 return;
3714 }
3715
3716 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3717 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3718 // Only one pointer and no change in count so it must have the same id as before.
3719 uint32_t id = last->rawPointerData.pointers[0].id;
3720 current->rawPointerData.pointers[0].id = id;
3721 current->rawPointerData.idToIndex[id] = 0;
3722 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3723 return;
3724 }
3725
3726 // General case.
3727 // We build a heap of squared euclidean distances between current and last pointers
3728 // associated with the current and last pointer indices. Then, we find the best
3729 // match (by distance) for each current pointer.
3730 // The pointers must have the same tool type but it is possible for them to
3731 // transition from hovering to touching or vice-versa while retaining the same id.
3732 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3733
3734 uint32_t heapSize = 0;
3735 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3736 currentPointerIndex++) {
3737 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3738 lastPointerIndex++) {
3739 const RawPointerData::Pointer& currentPointer =
3740 current->rawPointerData.pointers[currentPointerIndex];
3741 const RawPointerData::Pointer& lastPointer =
3742 last->rawPointerData.pointers[lastPointerIndex];
3743 if (currentPointer.toolType == lastPointer.toolType) {
3744 int64_t deltaX = currentPointer.x - lastPointer.x;
3745 int64_t deltaY = currentPointer.y - lastPointer.y;
3746
3747 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3748
3749 // Insert new element into the heap (sift up).
3750 heap[heapSize].currentPointerIndex = currentPointerIndex;
3751 heap[heapSize].lastPointerIndex = lastPointerIndex;
3752 heap[heapSize].distance = distance;
3753 heapSize += 1;
3754 }
3755 }
3756 }
3757
3758 // Heapify
3759 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3760 startIndex -= 1;
3761 for (uint32_t parentIndex = startIndex;;) {
3762 uint32_t childIndex = parentIndex * 2 + 1;
3763 if (childIndex >= heapSize) {
3764 break;
3765 }
3766
3767 if (childIndex + 1 < heapSize &&
3768 heap[childIndex + 1].distance < heap[childIndex].distance) {
3769 childIndex += 1;
3770 }
3771
3772 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3773 break;
3774 }
3775
3776 swap(heap[parentIndex], heap[childIndex]);
3777 parentIndex = childIndex;
3778 }
3779 }
3780
3781#if DEBUG_POINTER_ASSIGNMENT
3782 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3783 for (size_t i = 0; i < heapSize; i++) {
3784 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3785 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3786 }
3787#endif
3788
3789 // Pull matches out by increasing order of distance.
3790 // To avoid reassigning pointers that have already been matched, the loop keeps track
3791 // of which last and current pointers have been matched using the matchedXXXBits variables.
3792 // It also tracks the used pointer id bits.
3793 BitSet32 matchedLastBits(0);
3794 BitSet32 matchedCurrentBits(0);
3795 BitSet32 usedIdBits(0);
3796 bool first = true;
3797 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3798 while (heapSize > 0) {
3799 if (first) {
3800 // The first time through the loop, we just consume the root element of
3801 // the heap (the one with smallest distance).
3802 first = false;
3803 } else {
3804 // Previous iterations consumed the root element of the heap.
3805 // Pop root element off of the heap (sift down).
3806 heap[0] = heap[heapSize];
3807 for (uint32_t parentIndex = 0;;) {
3808 uint32_t childIndex = parentIndex * 2 + 1;
3809 if (childIndex >= heapSize) {
3810 break;
3811 }
3812
3813 if (childIndex + 1 < heapSize &&
3814 heap[childIndex + 1].distance < heap[childIndex].distance) {
3815 childIndex += 1;
3816 }
3817
3818 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3819 break;
3820 }
3821
3822 swap(heap[parentIndex], heap[childIndex]);
3823 parentIndex = childIndex;
3824 }
3825
3826#if DEBUG_POINTER_ASSIGNMENT
3827 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003828 for (size_t j = 0; j < heapSize; j++) {
3829 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3830 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003831 }
3832#endif
3833 }
3834
3835 heapSize -= 1;
3836
3837 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3838 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3839
3840 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3841 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3842
3843 matchedCurrentBits.markBit(currentPointerIndex);
3844 matchedLastBits.markBit(lastPointerIndex);
3845
3846 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3847 current->rawPointerData.pointers[currentPointerIndex].id = id;
3848 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3849 current->rawPointerData.markIdBit(id,
3850 current->rawPointerData.isHovering(
3851 currentPointerIndex));
3852 usedIdBits.markBit(id);
3853
3854#if DEBUG_POINTER_ASSIGNMENT
3855 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3856 ", distance=%" PRIu64,
3857 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3858#endif
3859 break;
3860 }
3861 }
3862
3863 // Assign fresh ids to pointers that were not matched in the process.
3864 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3865 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3866 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3867
3868 current->rawPointerData.pointers[currentPointerIndex].id = id;
3869 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3870 current->rawPointerData.markIdBit(id,
3871 current->rawPointerData.isHovering(currentPointerIndex));
3872
3873#if DEBUG_POINTER_ASSIGNMENT
3874 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3875#endif
3876 }
3877}
3878
3879int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3880 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3881 return AKEY_STATE_VIRTUAL;
3882 }
3883
3884 for (const VirtualKey& virtualKey : mVirtualKeys) {
3885 if (virtualKey.keyCode == keyCode) {
3886 return AKEY_STATE_UP;
3887 }
3888 }
3889
3890 return AKEY_STATE_UNKNOWN;
3891}
3892
3893int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3894 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3895 return AKEY_STATE_VIRTUAL;
3896 }
3897
3898 for (const VirtualKey& virtualKey : mVirtualKeys) {
3899 if (virtualKey.scanCode == scanCode) {
3900 return AKEY_STATE_UP;
3901 }
3902 }
3903
3904 return AKEY_STATE_UNKNOWN;
3905}
3906
3907bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3908 const int32_t* keyCodes, uint8_t* outFlags) {
3909 for (const VirtualKey& virtualKey : mVirtualKeys) {
3910 for (size_t i = 0; i < numCodes; i++) {
3911 if (virtualKey.keyCode == keyCodes[i]) {
3912 outFlags[i] = 1;
3913 }
3914 }
3915 }
3916
3917 return true;
3918}
3919
3920std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3921 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003922 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003923 return std::make_optional(mPointerController->getDisplayId());
3924 } else {
3925 return std::make_optional(mViewport.displayId);
3926 }
3927 }
3928 return std::nullopt;
3929}
3930
3931} // namespace android