blob: f6fa7a14d9af8b7f397ae7244f38b0ae4cf89743 [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
chaviw98318de2021-05-19 16:45:23 -050021#include <ftl/NamedEnum.h>
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070022#include "TouchInputMapper.h"
23
24#include "CursorButtonAccumulator.h"
25#include "CursorScrollAccumulator.h"
26#include "TouchButtonAccumulator.h"
27#include "TouchCursorInputMapperCommon.h"
28
29namespace android {
30
31// --- Constants ---
32
33// Maximum amount of latency to add to touch events while waiting for data from an
34// external stylus.
35static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
36
37// Maximum amount of time to wait on touch data before pushing out new pressure data.
38static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
39
40// Artificial latency on synthetic events created from stylus data without corresponding touch
41// data.
42static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
43
44// --- Static Definitions ---
45
46template <typename T>
47inline static void swap(T& a, T& b) {
48 T temp = a;
49 a = b;
50 b = temp;
51}
52
53static float calculateCommonVector(float a, float b) {
54 if (a > 0 && b > 0) {
55 return a < b ? a : b;
56 } else if (a < 0 && b < 0) {
57 return a > b ? a : b;
58 } else {
59 return 0;
60 }
61}
62
63inline static float distance(float x1, float y1, float x2, float y2) {
64 return hypotf(x1 - x2, y1 - y2);
65}
66
67inline static int32_t signExtendNybble(int32_t value) {
68 return value >= 8 ? value - 16 : value;
69}
70
71// --- RawPointerAxes ---
72
73RawPointerAxes::RawPointerAxes() {
74 clear();
75}
76
77void RawPointerAxes::clear() {
78 x.clear();
79 y.clear();
80 pressure.clear();
81 touchMajor.clear();
82 touchMinor.clear();
83 toolMajor.clear();
84 toolMinor.clear();
85 orientation.clear();
86 distance.clear();
87 tiltX.clear();
88 tiltY.clear();
89 trackingId.clear();
90 slot.clear();
91}
92
93// --- RawPointerData ---
94
95RawPointerData::RawPointerData() {
96 clear();
97}
98
99void RawPointerData::clear() {
100 pointerCount = 0;
101 clearIdBits();
102}
103
104void RawPointerData::copyFrom(const RawPointerData& other) {
105 pointerCount = other.pointerCount;
106 hoveringIdBits = other.hoveringIdBits;
107 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800108 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109
110 for (uint32_t i = 0; i < pointerCount; i++) {
111 pointers[i] = other.pointers[i];
112
113 int id = pointers[i].id;
114 idToIndex[id] = other.idToIndex[id];
115 }
116}
117
118void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
119 float x = 0, y = 0;
120 uint32_t count = touchingIdBits.count();
121 if (count) {
122 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
123 uint32_t id = idBits.clearFirstMarkedBit();
124 const Pointer& pointer = pointerForId(id);
125 x += pointer.x;
126 y += pointer.y;
127 }
128 x /= count;
129 y /= count;
130 }
131 *outX = x;
132 *outY = y;
133}
134
135// --- CookedPointerData ---
136
137CookedPointerData::CookedPointerData() {
138 clear();
139}
140
141void CookedPointerData::clear() {
142 pointerCount = 0;
143 hoveringIdBits.clear();
144 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800145 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000146 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700147}
148
149void CookedPointerData::copyFrom(const CookedPointerData& other) {
150 pointerCount = other.pointerCount;
151 hoveringIdBits = other.hoveringIdBits;
152 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000153 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700154
155 for (uint32_t i = 0; i < pointerCount; i++) {
156 pointerProperties[i].copyFrom(other.pointerProperties[i]);
157 pointerCoords[i].copyFrom(other.pointerCoords[i]);
158
159 int id = pointerProperties[i].id;
160 idToIndex[id] = other.idToIndex[id];
161 }
162}
163
164// --- TouchInputMapper ---
165
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800166TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
167 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700168 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100169 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800170 mRawSurfaceWidth(-1),
171 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700172 mSurfaceLeft(0),
173 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700174 mSurfaceRight(0),
175 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700176 mPhysicalWidth(-1),
177 mPhysicalHeight(-1),
178 mPhysicalLeft(0),
179 mPhysicalTop(0),
180 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
181
182TouchInputMapper::~TouchInputMapper() {}
183
184uint32_t TouchInputMapper::getSources() {
185 return mSource;
186}
187
188void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
189 InputMapper::populateDeviceInfo(info);
190
Michael Wright227c5542020-07-02 18:30:52 +0100191 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 info->addMotionRange(mOrientedRanges.x);
193 info->addMotionRange(mOrientedRanges.y);
194 info->addMotionRange(mOrientedRanges.pressure);
195
Chris Yef74dc422020-09-02 22:41:50 -0700196 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700197 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
198 //
199 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
200 // motion, i.e. the hardware dimensions, as the finger could move completely across the
201 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700202 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
203 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
204 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
205 x.fuzz, x.resolution);
206 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
207 y.fuzz, y.resolution);
208 }
209
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700210 if (mOrientedRanges.haveSize) {
211 info->addMotionRange(mOrientedRanges.size);
212 }
213
214 if (mOrientedRanges.haveTouchSize) {
215 info->addMotionRange(mOrientedRanges.touchMajor);
216 info->addMotionRange(mOrientedRanges.touchMinor);
217 }
218
219 if (mOrientedRanges.haveToolSize) {
220 info->addMotionRange(mOrientedRanges.toolMajor);
221 info->addMotionRange(mOrientedRanges.toolMinor);
222 }
223
224 if (mOrientedRanges.haveOrientation) {
225 info->addMotionRange(mOrientedRanges.orientation);
226 }
227
228 if (mOrientedRanges.haveDistance) {
229 info->addMotionRange(mOrientedRanges.distance);
230 }
231
232 if (mOrientedRanges.haveTilt) {
233 info->addMotionRange(mOrientedRanges.tilt);
234 }
235
236 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
237 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
238 0.0f);
239 }
240 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
241 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
242 0.0f);
243 }
Michael Wright227c5542020-07-02 18:30:52 +0100244 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700245 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
246 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
247 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
248 x.fuzz, x.resolution);
249 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
250 y.fuzz, y.resolution);
251 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
252 x.fuzz, x.resolution);
253 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
254 y.fuzz, y.resolution);
255 }
256 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
257 }
258}
259
260void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700261 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
262 NamedEnum::string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700263 dumpParameters(dump);
264 dumpVirtualKeys(dump);
265 dumpRawPointerAxes(dump);
266 dumpCalibration(dump);
267 dumpAffineTransformation(dump);
268 dumpSurface(dump);
269
270 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
271 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
272 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
273 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
274 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
275 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
276 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
277 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
278 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
279 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
280 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
281 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
282 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
283 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
284 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
285 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
286 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
287
288 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
289 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
290 mLastRawState.rawPointerData.pointerCount);
291 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
292 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
293 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
294 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
295 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
296 "toolType=%d, isHovering=%s\n",
297 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
298 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
299 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
300 pointer.distance, pointer.toolType, toString(pointer.isHovering));
301 }
302
303 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
304 mLastCookedState.buttonState);
305 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
306 mLastCookedState.cookedPointerData.pointerCount);
307 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
308 const PointerProperties& pointerProperties =
309 mLastCookedState.cookedPointerData.pointerProperties[i];
310 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000311 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
312 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
313 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
315 "toolType=%d, isHovering=%s\n",
316 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
327 pointerProperties.toolType,
328 toString(mLastCookedState.cookedPointerData.isHovering(i)));
329 }
330
331 dump += INDENT3 "Stylus Fusion:\n";
332 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
333 toString(mExternalStylusConnected));
334 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
335 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
336 mExternalStylusFusionTimeout);
337 dump += INDENT3 "External Stylus State:\n";
338 dumpStylusState(dump, mExternalStylusState);
339
Michael Wright227c5542020-07-02 18:30:52 +0100340 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
342 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
343 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
344 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
345 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
346 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
347 }
348}
349
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
351 uint32_t changes) {
352 InputMapper::configure(when, config, changes);
353
354 mConfig = *config;
355
356 if (!changes) { // first time only
357 // Configure basic parameters.
358 configureParameters();
359
360 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mCursorScrollAccumulator.configure(getDeviceContext());
362 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700363
364 // Configure absolute axis information.
365 configureRawPointerAxes();
366
367 // Prepare input device calibration.
368 parseCalibration();
369 resolveCalibration();
370 }
371
372 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
373 // Update location calibration to reflect current settings
374 updateAffineTransformation();
375 }
376
377 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
378 // Update pointer speed.
379 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
380 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
381 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 }
383
384 bool resetNeeded = false;
385 if (!changes ||
386 (changes &
387 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800388 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
390 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
391 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
392 // Configure device sources, surface dimensions, orientation and
393 // scaling factors.
394 configureSurface(when, &resetNeeded);
395 }
396
397 if (changes && resetNeeded) {
398 // Send reset, unless this is the first time the device has been configured,
399 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +0000400 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
401 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
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700473 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
474 String8 orientationString;
475 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientation"),
476 orientationString)) {
477 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
478 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
479 } else if (orientationString == "ORIENTATION_90") {
480 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
481 } else if (orientationString == "ORIENTATION_180") {
482 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
483 } else if (orientationString == "ORIENTATION_270") {
484 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
485 } else if (orientationString != "ORIENTATION_0") {
486 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.string());
487 }
488 }
489
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700490 mParameters.hasAssociatedDisplay = false;
491 mParameters.associatedDisplayIsExternal = false;
492 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100493 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
494 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700495 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100496 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800497 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700498 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800499 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
500 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700501 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
502 }
503 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800504 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700505 mParameters.hasAssociatedDisplay = true;
506 }
507
508 // Initial downs on external touch devices should wake the device.
509 // Normally we don't do this for internal touch screens to prevent them from waking
510 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800511 mParameters.wake = getDeviceContext().isExternal();
512 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700513}
514
515void TouchInputMapper::dumpParameters(std::string& dump) {
516 dump += INDENT3 "Parameters:\n";
517
Chris Yea03dd232020-09-08 19:21:09 -0700518 dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700519
Chris Yea03dd232020-09-08 19:21:09 -0700520 dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700521
522 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
523 "displayId='%s'\n",
524 toString(mParameters.hasAssociatedDisplay),
525 toString(mParameters.associatedDisplayIsExternal),
526 mParameters.uniqueDisplayId.c_str());
527 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700528 dump += INDENT4 "Orientation: " + NamedEnum::string(mParameters.orientation) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700529}
530
531void TouchInputMapper::configureRawPointerAxes() {
532 mRawPointerAxes.clear();
533}
534
535void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
536 dump += INDENT3 "Raw Touch Axes:\n";
537 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
538 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
549 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
550}
551
552bool TouchInputMapper::hasExternalStylus() const {
553 return mExternalStylusConnected;
554}
555
556/**
557 * Determine which DisplayViewport to use.
558 * 1. If display port is specified, return the matching viewport. If matching viewport not
559 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800560 * 2. Always use the suggested viewport from WindowManagerService for pointers.
561 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700562 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800563 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 */
565std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800566 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800567 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700568 if (displayPort) {
569 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800570 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700571 }
572
Michael Wright227c5542020-07-02 18:30:52 +0100573 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800574 std::optional<DisplayViewport> viewport =
575 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
576 if (viewport) {
577 return viewport;
578 } else {
579 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
580 mConfig.defaultPointerDisplayId);
581 }
582 }
583
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700584 // Check if uniqueDisplayId is specified in idc file.
585 if (!mParameters.uniqueDisplayId.empty()) {
586 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
587 }
588
589 ViewportType viewportTypeToUse;
590 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100591 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700592 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100593 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700594 }
595
596 std::optional<DisplayViewport> viewport =
597 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100598 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700599 ALOGW("Input device %s should be associated with external display, "
600 "fallback to internal one for the external viewport is not found.",
601 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100602 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700603 }
604
605 return viewport;
606 }
607
608 // No associated display, return a non-display viewport.
609 DisplayViewport newViewport;
610 // Raw width and height in the natural orientation.
611 int32_t rawWidth = mRawPointerAxes.getRawWidth();
612 int32_t rawHeight = mRawPointerAxes.getRawHeight();
613 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
614 return std::make_optional(newViewport);
615}
616
617void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100618 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700619
620 resolveExternalStylusPresence();
621
622 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100623 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800624 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700625 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100626 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700627 if (hasStylus()) {
628 mSource |= AINPUT_SOURCE_STYLUS;
629 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800630 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700631 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100632 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700633 if (hasStylus()) {
634 mSource |= AINPUT_SOURCE_STYLUS;
635 }
636 if (hasExternalStylus()) {
637 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
638 }
Michael Wright227c5542020-07-02 18:30:52 +0100639 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700640 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100641 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700642 } else {
643 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100644 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700645 }
646
647 // Ensure we have valid X and Y axes.
648 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
649 ALOGW("Touch device '%s' did not report support for X or Y axis! "
650 "The device will be inoperable.",
651 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100652 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700653 return;
654 }
655
656 // Get associated display dimensions.
657 std::optional<DisplayViewport> newViewport = findViewport();
658 if (!newViewport) {
659 ALOGI("Touch device '%s' could not query the properties of its associated "
660 "display. The device will be inoperable until the display size "
661 "becomes available.",
662 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100663 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700664 return;
665 }
666
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000667 if (!newViewport->isActive) {
668 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
669 getDeviceName().c_str(), getDeviceId());
670 mDeviceMode = DeviceMode::DISABLED;
671 return;
672 }
673
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700674 // Raw width and height in the natural orientation.
675 int32_t rawWidth = mRawPointerAxes.getRawWidth();
676 int32_t rawHeight = mRawPointerAxes.getRawHeight();
677
678 bool viewportChanged = mViewport != *newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700679 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700680 if (viewportChanged) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700681 bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700682 mViewport = *newViewport;
683
Michael Wright227c5542020-07-02 18:30:52 +0100684 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700685 // Convert rotated viewport to natural surface coordinates.
686 int32_t naturalLogicalWidth, naturalLogicalHeight;
687 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
688 int32_t naturalPhysicalLeft, naturalPhysicalTop;
689 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700690
691 // Apply the inverse of the input device orientation so that the surface is configured
692 // in the same orientation as the device. The input device orientation will be
693 // re-applied to mSurfaceOrientation.
694 const int32_t naturalSurfaceOrientation =
695 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
696 switch (naturalSurfaceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700697 case DISPLAY_ORIENTATION_90:
698 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
699 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
700 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
701 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800702 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700703 naturalPhysicalTop = mViewport.physicalLeft;
704 naturalDeviceWidth = mViewport.deviceHeight;
705 naturalDeviceHeight = mViewport.deviceWidth;
706 break;
707 case DISPLAY_ORIENTATION_180:
708 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
709 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
710 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
711 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
712 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
713 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
714 naturalDeviceWidth = mViewport.deviceWidth;
715 naturalDeviceHeight = mViewport.deviceHeight;
716 break;
717 case DISPLAY_ORIENTATION_270:
718 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
719 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
720 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
721 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
722 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800723 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700724 naturalDeviceWidth = mViewport.deviceHeight;
725 naturalDeviceHeight = mViewport.deviceWidth;
726 break;
727 case DISPLAY_ORIENTATION_0:
728 default:
729 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
730 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
731 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
732 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
733 naturalPhysicalLeft = mViewport.physicalLeft;
734 naturalPhysicalTop = mViewport.physicalTop;
735 naturalDeviceWidth = mViewport.deviceWidth;
736 naturalDeviceHeight = mViewport.deviceHeight;
737 break;
738 }
739
740 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
741 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
742 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
743 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
744 }
745
746 mPhysicalWidth = naturalPhysicalWidth;
747 mPhysicalHeight = naturalPhysicalHeight;
748 mPhysicalLeft = naturalPhysicalLeft;
749 mPhysicalTop = naturalPhysicalTop;
750
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700751 const int32_t oldSurfaceWidth = mRawSurfaceWidth;
752 const int32_t oldSurfaceHeight = mRawSurfaceHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800753 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
754 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700755 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
756 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800757 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
758 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700759
Prabir Pradhand7482e72021-03-09 13:54:55 -0800760 if (isPerWindowInputRotationEnabled()) {
761 // When per-window input rotation is enabled, InputReader works in the un-rotated
762 // coordinate space, so we don't need to do anything if the device is already
763 // orientation-aware. If the device is not orientation-aware, then we need to apply
764 // the inverse rotation of the display so that when the display rotation is applied
765 // later as a part of the per-window transform, we get the expected screen
766 // coordinates.
767 mSurfaceOrientation = mParameters.orientationAware
768 ? DISPLAY_ORIENTATION_0
769 : getInverseRotation(mViewport.orientation);
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700770 // For orientation-aware devices that work in the un-rotated coordinate space, the
771 // viewport update should be skipped if it is only a change in the orientation.
772 skipViewportUpdate = mParameters.orientationAware &&
773 mRawSurfaceWidth == oldSurfaceWidth &&
774 mRawSurfaceHeight == oldSurfaceHeight && viewportOrientationChanged;
Prabir Pradhand7482e72021-03-09 13:54:55 -0800775 } else {
776 mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation
777 : DISPLAY_ORIENTATION_0;
778 }
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700779
780 // Apply the input device orientation for the device.
781 mSurfaceOrientation =
782 (mSurfaceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700783 } else {
784 mPhysicalWidth = rawWidth;
785 mPhysicalHeight = rawHeight;
786 mPhysicalLeft = 0;
787 mPhysicalTop = 0;
788
Arthur Hung4197f6b2020-03-16 15:39:59 +0800789 mRawSurfaceWidth = rawWidth;
790 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700791 mSurfaceLeft = 0;
792 mSurfaceTop = 0;
793 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
794 }
795 }
796
797 // If moving between pointer modes, need to reset some state.
798 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
799 if (deviceModeChanged) {
800 mOrientedRanges.clear();
801 }
802
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800803 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
804 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100805 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800806 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
807 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800808 if (mPointerController == nullptr) {
809 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700810 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800811 if (mConfig.pointerCapture) {
812 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
813 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700814 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100815 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700816 }
817
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700818 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700819 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
820 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800821 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700822 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
823
824 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800825 mXScale = float(mRawSurfaceWidth) / rawWidth;
826 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700827 mXTranslate = -mSurfaceLeft;
828 mYTranslate = -mSurfaceTop;
829 mXPrecision = 1.0f / mXScale;
830 mYPrecision = 1.0f / mYScale;
831
832 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
833 mOrientedRanges.x.source = mSource;
834 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
835 mOrientedRanges.y.source = mSource;
836
837 configureVirtualKeys();
838
839 // Scale factor for terms that are not oriented in a particular axis.
840 // If the pixels are square then xScale == yScale otherwise we fake it
841 // by choosing an average.
842 mGeometricScale = avg(mXScale, mYScale);
843
844 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800845 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700846
847 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100848 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700849 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
850 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
851 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
852 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
853 } else {
854 mSizeScale = 0.0f;
855 }
856
857 mOrientedRanges.haveTouchSize = true;
858 mOrientedRanges.haveToolSize = true;
859 mOrientedRanges.haveSize = true;
860
861 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
862 mOrientedRanges.touchMajor.source = mSource;
863 mOrientedRanges.touchMajor.min = 0;
864 mOrientedRanges.touchMajor.max = diagonalSize;
865 mOrientedRanges.touchMajor.flat = 0;
866 mOrientedRanges.touchMajor.fuzz = 0;
867 mOrientedRanges.touchMajor.resolution = 0;
868
869 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
870 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
871
872 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
873 mOrientedRanges.toolMajor.source = mSource;
874 mOrientedRanges.toolMajor.min = 0;
875 mOrientedRanges.toolMajor.max = diagonalSize;
876 mOrientedRanges.toolMajor.flat = 0;
877 mOrientedRanges.toolMajor.fuzz = 0;
878 mOrientedRanges.toolMajor.resolution = 0;
879
880 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
881 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
882
883 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
884 mOrientedRanges.size.source = mSource;
885 mOrientedRanges.size.min = 0;
886 mOrientedRanges.size.max = 1.0;
887 mOrientedRanges.size.flat = 0;
888 mOrientedRanges.size.fuzz = 0;
889 mOrientedRanges.size.resolution = 0;
890 } else {
891 mSizeScale = 0.0f;
892 }
893
894 // Pressure factors.
895 mPressureScale = 0;
896 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100897 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
898 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700899 if (mCalibration.havePressureScale) {
900 mPressureScale = mCalibration.pressureScale;
901 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
902 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
903 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
904 }
905 }
906
907 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
908 mOrientedRanges.pressure.source = mSource;
909 mOrientedRanges.pressure.min = 0;
910 mOrientedRanges.pressure.max = pressureMax;
911 mOrientedRanges.pressure.flat = 0;
912 mOrientedRanges.pressure.fuzz = 0;
913 mOrientedRanges.pressure.resolution = 0;
914
915 // Tilt
916 mTiltXCenter = 0;
917 mTiltXScale = 0;
918 mTiltYCenter = 0;
919 mTiltYScale = 0;
920 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
921 if (mHaveTilt) {
922 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
923 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
924 mTiltXScale = M_PI / 180;
925 mTiltYScale = M_PI / 180;
926
927 mOrientedRanges.haveTilt = true;
928
929 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
930 mOrientedRanges.tilt.source = mSource;
931 mOrientedRanges.tilt.min = 0;
932 mOrientedRanges.tilt.max = M_PI_2;
933 mOrientedRanges.tilt.flat = 0;
934 mOrientedRanges.tilt.fuzz = 0;
935 mOrientedRanges.tilt.resolution = 0;
936 }
937
938 // Orientation
939 mOrientationScale = 0;
940 if (mHaveTilt) {
941 mOrientedRanges.haveOrientation = true;
942
943 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
944 mOrientedRanges.orientation.source = mSource;
945 mOrientedRanges.orientation.min = -M_PI;
946 mOrientedRanges.orientation.max = M_PI;
947 mOrientedRanges.orientation.flat = 0;
948 mOrientedRanges.orientation.fuzz = 0;
949 mOrientedRanges.orientation.resolution = 0;
950 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100951 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700952 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100953 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700954 if (mRawPointerAxes.orientation.valid) {
955 if (mRawPointerAxes.orientation.maxValue > 0) {
956 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
957 } else if (mRawPointerAxes.orientation.minValue < 0) {
958 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
959 } else {
960 mOrientationScale = 0;
961 }
962 }
963 }
964
965 mOrientedRanges.haveOrientation = true;
966
967 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
968 mOrientedRanges.orientation.source = mSource;
969 mOrientedRanges.orientation.min = -M_PI_2;
970 mOrientedRanges.orientation.max = M_PI_2;
971 mOrientedRanges.orientation.flat = 0;
972 mOrientedRanges.orientation.fuzz = 0;
973 mOrientedRanges.orientation.resolution = 0;
974 }
975
976 // Distance
977 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100978 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
979 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700980 if (mCalibration.haveDistanceScale) {
981 mDistanceScale = mCalibration.distanceScale;
982 } else {
983 mDistanceScale = 1.0f;
984 }
985 }
986
987 mOrientedRanges.haveDistance = true;
988
989 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
990 mOrientedRanges.distance.source = mSource;
991 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
992 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
993 mOrientedRanges.distance.flat = 0;
994 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
995 mOrientedRanges.distance.resolution = 0;
996 }
997
998 // Compute oriented precision, scales and ranges.
999 // Note that the maximum value reported is an inclusive maximum value so it is one
1000 // unit less than the total width or height of surface.
1001 switch (mSurfaceOrientation) {
1002 case DISPLAY_ORIENTATION_90:
1003 case DISPLAY_ORIENTATION_270:
1004 mOrientedXPrecision = mYPrecision;
1005 mOrientedYPrecision = mXPrecision;
1006
1007 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001008 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001009 mOrientedRanges.x.flat = 0;
1010 mOrientedRanges.x.fuzz = 0;
1011 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
1012
1013 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001014 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001015 mOrientedRanges.y.flat = 0;
1016 mOrientedRanges.y.fuzz = 0;
1017 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
1018 break;
1019
1020 default:
1021 mOrientedXPrecision = mXPrecision;
1022 mOrientedYPrecision = mYPrecision;
1023
1024 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001025 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001026 mOrientedRanges.x.flat = 0;
1027 mOrientedRanges.x.fuzz = 0;
1028 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1029
1030 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001031 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032 mOrientedRanges.y.flat = 0;
1033 mOrientedRanges.y.fuzz = 0;
1034 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1035 break;
1036 }
1037
1038 // Location
1039 updateAffineTransformation();
1040
Michael Wright227c5542020-07-02 18:30:52 +01001041 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001042 // Compute pointer gesture detection parameters.
1043 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001044 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001045
1046 // Scale movements such that one whole swipe of the touch pad covers a
1047 // given area relative to the diagonal size of the display when no acceleration
1048 // is applied.
1049 // Assume that the touch pad has a square aspect ratio such that movements in
1050 // X and Y of the same number of raw units cover the same physical distance.
1051 mPointerXMovementScale =
1052 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1053 mPointerYMovementScale = mPointerXMovementScale;
1054
1055 // Scale zooms to cover a smaller range of the display than movements do.
1056 // This value determines the area around the pointer that is affected by freeform
1057 // pointer gestures.
1058 mPointerXZoomScale =
1059 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1060 mPointerYZoomScale = mPointerXZoomScale;
1061
1062 // Max width between pointers to detect a swipe gesture is more than some fraction
1063 // of the diagonal axis of the touch pad. Touches that are wider than this are
1064 // translated into freeform gestures.
1065 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1066
1067 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001068 const nsecs_t readTime = when; // synthetic event
1069 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001070 }
1071
1072 // Inform the dispatcher about the changes.
1073 *outResetNeeded = true;
1074 bumpGeneration();
1075 }
1076}
1077
1078void TouchInputMapper::dumpSurface(std::string& dump) {
1079 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001080 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1081 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1083 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001084 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1085 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1087 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1088 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1089 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1090 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1091}
1092
1093void TouchInputMapper::configureVirtualKeys() {
1094 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001095 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001096
1097 mVirtualKeys.clear();
1098
1099 if (virtualKeyDefinitions.size() == 0) {
1100 return;
1101 }
1102
1103 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1104 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1105 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1106 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1107
1108 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1109 VirtualKey virtualKey;
1110
1111 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1112 int32_t keyCode;
1113 int32_t dummyKeyMetaState;
1114 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001115 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1116 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1118 continue; // drop the key
1119 }
1120
1121 virtualKey.keyCode = keyCode;
1122 virtualKey.flags = flags;
1123
1124 // convert the key definition's display coordinates into touch coordinates for a hit box
1125 int32_t halfWidth = virtualKeyDefinition.width / 2;
1126 int32_t halfHeight = virtualKeyDefinition.height / 2;
1127
1128 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001129 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001130 touchScreenLeft;
1131 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001132 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001134 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1135 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001137 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1138 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 touchScreenTop;
1140 mVirtualKeys.push_back(virtualKey);
1141 }
1142}
1143
1144void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1145 if (!mVirtualKeys.empty()) {
1146 dump += INDENT3 "Virtual Keys:\n";
1147
1148 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1149 const VirtualKey& virtualKey = mVirtualKeys[i];
1150 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1151 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1152 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1153 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1154 }
1155 }
1156}
1157
1158void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001159 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 Calibration& out = mCalibration;
1161
1162 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001164 String8 sizeCalibrationString;
1165 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1166 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (sizeCalibrationString != "default") {
1177 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1178 }
1179 }
1180
1181 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1182 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1183 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1184
1185 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001186 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001187 String8 pressureCalibrationString;
1188 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1189 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001194 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 } else if (pressureCalibrationString != "default") {
1196 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1197 pressureCalibrationString.string());
1198 }
1199 }
1200
1201 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1202
1203 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 String8 orientationCalibrationString;
1206 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1207 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 } else if (orientationCalibrationString != "default") {
1214 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1215 orientationCalibrationString.string());
1216 }
1217 }
1218
1219 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001220 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 String8 distanceCalibrationString;
1222 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1223 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001226 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 } else if (distanceCalibrationString != "default") {
1228 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1229 distanceCalibrationString.string());
1230 }
1231 }
1232
1233 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1234
Michael Wright227c5542020-07-02 18:30:52 +01001235 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 String8 coverageCalibrationString;
1237 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1238 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001239 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001241 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 } else if (coverageCalibrationString != "default") {
1243 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1244 coverageCalibrationString.string());
1245 }
1246 }
1247}
1248
1249void TouchInputMapper::resolveCalibration() {
1250 // Size
1251 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001252 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1253 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 }
1255 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001256 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258
1259 // Pressure
1260 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001261 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1262 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 }
1264 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001265 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267
1268 // Orientation
1269 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001270 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1271 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 }
1273 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001274 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 }
1276
1277 // Distance
1278 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001279 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1280 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 }
1282 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001283 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285
1286 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001287 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1288 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 }
1290}
1291
1292void TouchInputMapper::dumpCalibration(std::string& dump) {
1293 dump += INDENT3 "Calibration:\n";
1294
1295 // Size
1296 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001297 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += INDENT4 "touch.size.calibration: none\n";
1299 break;
Michael Wright227c5542020-07-02 18:30:52 +01001300 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += INDENT4 "touch.size.calibration: geometric\n";
1302 break;
Michael Wright227c5542020-07-02 18:30:52 +01001303 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += INDENT4 "touch.size.calibration: diameter\n";
1305 break;
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.size.calibration: box\n";
1308 break;
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.size.calibration: area\n";
1311 break;
1312 default:
1313 ALOG_ASSERT(false);
1314 }
1315
1316 if (mCalibration.haveSizeScale) {
1317 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1318 }
1319
1320 if (mCalibration.haveSizeBias) {
1321 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1322 }
1323
1324 if (mCalibration.haveSizeIsSummed) {
1325 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1326 toString(mCalibration.sizeIsSummed));
1327 }
1328
1329 // Pressure
1330 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.pressure.calibration: none\n";
1333 break;
Michael Wright227c5542020-07-02 18:30:52 +01001334 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001335 dump += INDENT4 "touch.pressure.calibration: physical\n";
1336 break;
Michael Wright227c5542020-07-02 18:30:52 +01001337 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1339 break;
1340 default:
1341 ALOG_ASSERT(false);
1342 }
1343
1344 if (mCalibration.havePressureScale) {
1345 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1346 }
1347
1348 // Orientation
1349 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001350 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001351 dump += INDENT4 "touch.orientation.calibration: none\n";
1352 break;
Michael Wright227c5542020-07-02 18:30:52 +01001353 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001354 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1355 break;
Michael Wright227c5542020-07-02 18:30:52 +01001356 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 dump += INDENT4 "touch.orientation.calibration: vector\n";
1358 break;
1359 default:
1360 ALOG_ASSERT(false);
1361 }
1362
1363 // Distance
1364 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001365 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366 dump += INDENT4 "touch.distance.calibration: none\n";
1367 break;
Michael Wright227c5542020-07-02 18:30:52 +01001368 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001369 dump += INDENT4 "touch.distance.calibration: scaled\n";
1370 break;
1371 default:
1372 ALOG_ASSERT(false);
1373 }
1374
1375 if (mCalibration.haveDistanceScale) {
1376 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1377 }
1378
1379 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001380 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001381 dump += INDENT4 "touch.coverage.calibration: none\n";
1382 break;
Michael Wright227c5542020-07-02 18:30:52 +01001383 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001384 dump += INDENT4 "touch.coverage.calibration: box\n";
1385 break;
1386 default:
1387 ALOG_ASSERT(false);
1388 }
1389}
1390
1391void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1392 dump += INDENT3 "Affine Transformation:\n";
1393
1394 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1395 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1396 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1397 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1398 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1399 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1400}
1401
1402void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001403 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001404 mSurfaceOrientation);
1405}
1406
1407void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001408 mCursorButtonAccumulator.reset(getDeviceContext());
1409 mCursorScrollAccumulator.reset(getDeviceContext());
1410 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411
1412 mPointerVelocityControl.reset();
1413 mWheelXVelocityControl.reset();
1414 mWheelYVelocityControl.reset();
1415
1416 mRawStatesPending.clear();
1417 mCurrentRawState.clear();
1418 mCurrentCookedState.clear();
1419 mLastRawState.clear();
1420 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001421 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422 mSentHoverEnter = false;
1423 mHavePointerIds = false;
1424 mCurrentMotionAborted = false;
1425 mDownTime = 0;
1426
1427 mCurrentVirtualKey.down = false;
1428
1429 mPointerGesture.reset();
1430 mPointerSimple.reset();
1431 resetExternalStylus();
1432
1433 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001434 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001435 mPointerController->clearSpots();
1436 }
1437
1438 InputMapper::reset(when);
1439}
1440
1441void TouchInputMapper::resetExternalStylus() {
1442 mExternalStylusState.clear();
1443 mExternalStylusId = -1;
1444 mExternalStylusFusionTimeout = LLONG_MAX;
1445 mExternalStylusDataPending = false;
1446}
1447
1448void TouchInputMapper::clearStylusDataPendingFlags() {
1449 mExternalStylusDataPending = false;
1450 mExternalStylusFusionTimeout = LLONG_MAX;
1451}
1452
1453void TouchInputMapper::process(const RawEvent* rawEvent) {
1454 mCursorButtonAccumulator.process(rawEvent);
1455 mCursorScrollAccumulator.process(rawEvent);
1456 mTouchButtonAccumulator.process(rawEvent);
1457
1458 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001459 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001460 }
1461}
1462
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001463void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001464 // Push a new state.
1465 mRawStatesPending.emplace_back();
1466
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001467 RawState& next = mRawStatesPending.back();
1468 next.clear();
1469 next.when = when;
1470 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001471
1472 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001473 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001474 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1475
1476 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001477 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1478 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479 mCursorScrollAccumulator.finishSync();
1480
1481 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001482 syncTouch(when, &next);
1483
1484 // The last RawState is the actually second to last, since we just added a new state
1485 const RawState& last =
1486 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001487
1488 // Assign pointer ids.
1489 if (!mHavePointerIds) {
1490 assignPointerIds(last, next);
1491 }
1492
1493#if DEBUG_RAW_EVENTS
1494 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001495 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001496 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1497 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1498 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1499 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001500#endif
1501
Arthur Hung9ad18942021-06-19 02:04:46 +00001502 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1503 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1504 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1505 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1506 next.rawPointerData.hoveringIdBits.value);
1507 }
1508
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001509 processRawTouches(false /*timeout*/);
1510}
1511
1512void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001513 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001514 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001515 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001516 mCurrentCookedState.clear();
1517 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001518 return;
1519 }
1520
1521 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1522 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1523 // touching the current state will only observe the events that have been dispatched to the
1524 // rest of the pipeline.
1525 const size_t N = mRawStatesPending.size();
1526 size_t count;
1527 for (count = 0; count < N; count++) {
1528 const RawState& next = mRawStatesPending[count];
1529
1530 // A failure to assign the stylus id means that we're waiting on stylus data
1531 // and so should defer the rest of the pipeline.
1532 if (assignExternalStylusId(next, timeout)) {
1533 break;
1534 }
1535
1536 // All ready to go.
1537 clearStylusDataPendingFlags();
1538 mCurrentRawState.copyFrom(next);
1539 if (mCurrentRawState.when < mLastRawState.when) {
1540 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001541 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001542 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001543 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001544 }
1545 if (count != 0) {
1546 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1547 }
1548
1549 if (mExternalStylusDataPending) {
1550 if (timeout) {
1551 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1552 clearStylusDataPendingFlags();
1553 mCurrentRawState.copyFrom(mLastRawState);
1554#if DEBUG_STYLUS_FUSION
1555 ALOGD("Timeout expired, synthesizing event with new stylus data");
1556#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001557 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1558 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001559 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1560 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1561 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1562 }
1563 }
1564}
1565
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001566void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001567 // Always start with a clean state.
1568 mCurrentCookedState.clear();
1569
1570 // Apply stylus buttons to current raw state.
1571 applyExternalStylusButtonState(when);
1572
1573 // Handle policy on initial down or hover events.
1574 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1575 mCurrentRawState.rawPointerData.pointerCount != 0;
1576
1577 uint32_t policyFlags = 0;
1578 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1579 if (initialDown || buttonsPressed) {
1580 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001581 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001582 getContext()->fadePointer();
1583 }
1584
1585 if (mParameters.wake) {
1586 policyFlags |= POLICY_FLAG_WAKE;
1587 }
1588 }
1589
1590 // Consume raw off-screen touches before cooking pointer data.
1591 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001592 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001593 mCurrentRawState.rawPointerData.clear();
1594 }
1595
1596 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1597 // with cooked pointer data that has the same ids and indices as the raw data.
1598 // The following code can use either the raw or cooked data, as needed.
1599 cookPointerData();
1600
1601 // Apply stylus pressure to current cooked state.
1602 applyExternalStylusTouchState(when);
1603
1604 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001605 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1606 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001607 mCurrentCookedState.buttonState);
1608
1609 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001610 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001611 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1612 uint32_t id = idBits.clearFirstMarkedBit();
1613 const RawPointerData::Pointer& pointer =
1614 mCurrentRawState.rawPointerData.pointerForId(id);
1615 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1616 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1617 mCurrentCookedState.stylusIdBits.markBit(id);
1618 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1619 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1620 mCurrentCookedState.fingerIdBits.markBit(id);
1621 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1622 mCurrentCookedState.mouseIdBits.markBit(id);
1623 }
1624 }
1625 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1626 uint32_t id = idBits.clearFirstMarkedBit();
1627 const RawPointerData::Pointer& pointer =
1628 mCurrentRawState.rawPointerData.pointerForId(id);
1629 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1630 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1631 mCurrentCookedState.stylusIdBits.markBit(id);
1632 }
1633 }
1634
1635 // Stylus takes precedence over all tools, then mouse, then finger.
1636 PointerUsage pointerUsage = mPointerUsage;
1637 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1638 mCurrentCookedState.mouseIdBits.clear();
1639 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001640 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001641 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1642 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001643 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001644 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1645 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001646 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647 }
1648
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001649 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001650 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001651 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001652
1653 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001654 dispatchButtonRelease(when, readTime, policyFlags);
1655 dispatchHoverExit(when, readTime, policyFlags);
1656 dispatchTouches(when, readTime, policyFlags);
1657 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1658 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001659 }
1660
1661 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1662 mCurrentMotionAborted = false;
1663 }
1664 }
1665
1666 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001667 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001668 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1669 mCurrentCookedState.buttonState);
1670
1671 // Clear some transient state.
1672 mCurrentRawState.rawVScroll = 0;
1673 mCurrentRawState.rawHScroll = 0;
1674
1675 // Copy current touch to last touch in preparation for the next cycle.
1676 mLastRawState.copyFrom(mCurrentRawState);
1677 mLastCookedState.copyFrom(mCurrentCookedState);
1678}
1679
Garfield Tanc734e4f2021-01-15 20:01:39 -08001680void TouchInputMapper::updateTouchSpots() {
1681 if (!mConfig.showTouches || mPointerController == nullptr) {
1682 return;
1683 }
1684
1685 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1686 // clear touch spots.
1687 if (mDeviceMode != DeviceMode::DIRECT &&
1688 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1689 return;
1690 }
1691
1692 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1693 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1694
1695 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001696 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1697 mCurrentCookedState.cookedPointerData.idToIndex,
1698 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001699}
1700
1701bool TouchInputMapper::isTouchScreen() {
1702 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1703 mParameters.hasAssociatedDisplay;
1704}
1705
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001706void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001707 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001708 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1709 }
1710}
1711
1712void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1713 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1714 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1715
1716 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1717 float pressure = mExternalStylusState.pressure;
1718 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1719 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1720 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1721 }
1722 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1723 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1724
1725 PointerProperties& properties =
1726 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1727 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1728 properties.toolType = mExternalStylusState.toolType;
1729 }
1730 }
1731}
1732
1733bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001734 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001735 return false;
1736 }
1737
1738 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1739 state.rawPointerData.pointerCount != 0;
1740 if (initialDown) {
1741 if (mExternalStylusState.pressure != 0.0f) {
1742#if DEBUG_STYLUS_FUSION
1743 ALOGD("Have both stylus and touch data, beginning fusion");
1744#endif
1745 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1746 } else if (timeout) {
1747#if DEBUG_STYLUS_FUSION
1748 ALOGD("Timeout expired, assuming touch is not a stylus.");
1749#endif
1750 resetExternalStylus();
1751 } else {
1752 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1753 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1754 }
1755#if DEBUG_STYLUS_FUSION
1756 ALOGD("No stylus data but stylus is connected, requesting timeout "
1757 "(%" PRId64 "ms)",
1758 mExternalStylusFusionTimeout);
1759#endif
1760 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1761 return true;
1762 }
1763 }
1764
1765 // Check if the stylus pointer has gone up.
1766 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1767#if DEBUG_STYLUS_FUSION
1768 ALOGD("Stylus pointer is going up");
1769#endif
1770 mExternalStylusId = -1;
1771 }
1772
1773 return false;
1774}
1775
1776void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001777 if (mDeviceMode == DeviceMode::POINTER) {
1778 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001779 // Since this is a synthetic event, we can consider its latency to be zero
1780 const nsecs_t readTime = when;
1781 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001782 }
Michael Wright227c5542020-07-02 18:30:52 +01001783 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001784 if (mExternalStylusFusionTimeout < when) {
1785 processRawTouches(true /*timeout*/);
1786 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1787 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1788 }
1789 }
1790}
1791
1792void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1793 mExternalStylusState.copyFrom(state);
1794 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1795 // We're either in the middle of a fused stream of data or we're waiting on data before
1796 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1797 // data.
1798 mExternalStylusDataPending = true;
1799 processRawTouches(false /*timeout*/);
1800 }
1801}
1802
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001803bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001804 // Check for release of a virtual key.
1805 if (mCurrentVirtualKey.down) {
1806 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1807 // Pointer went up while virtual key was down.
1808 mCurrentVirtualKey.down = false;
1809 if (!mCurrentVirtualKey.ignored) {
1810#if DEBUG_VIRTUAL_KEYS
1811 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1812 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1813#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001814 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001815 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1816 }
1817 return true;
1818 }
1819
1820 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1821 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1822 const RawPointerData::Pointer& pointer =
1823 mCurrentRawState.rawPointerData.pointerForId(id);
1824 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1825 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1826 // Pointer is still within the space of the virtual key.
1827 return true;
1828 }
1829 }
1830
1831 // Pointer left virtual key area or another pointer also went down.
1832 // Send key cancellation but do not consume the touch yet.
1833 // This is useful when the user swipes through from the virtual key area
1834 // into the main display surface.
1835 mCurrentVirtualKey.down = false;
1836 if (!mCurrentVirtualKey.ignored) {
1837#if DEBUG_VIRTUAL_KEYS
1838 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1839 mCurrentVirtualKey.scanCode);
1840#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001841 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001842 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1843 AKEY_EVENT_FLAG_CANCELED);
1844 }
1845 }
1846
1847 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1848 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1849 // Pointer just went down. Check for virtual key press or off-screen touches.
1850 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1851 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001852 // Exclude unscaled device for inside surface checking.
1853 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854 // If exactly one pointer went down, check for virtual key hit.
1855 // Otherwise we will drop the entire stroke.
1856 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1857 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1858 if (virtualKey) {
1859 mCurrentVirtualKey.down = true;
1860 mCurrentVirtualKey.downTime = when;
1861 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1862 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1863 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001864 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1865 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001866
1867 if (!mCurrentVirtualKey.ignored) {
1868#if DEBUG_VIRTUAL_KEYS
1869 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1870 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1871#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001872 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001873 AKEY_EVENT_FLAG_FROM_SYSTEM |
1874 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1875 }
1876 }
1877 }
1878 return true;
1879 }
1880 }
1881
1882 // Disable all virtual key touches that happen within a short time interval of the
1883 // most recent touch within the screen area. The idea is to filter out stray
1884 // virtual key presses when interacting with the touch screen.
1885 //
1886 // Problems we're trying to solve:
1887 //
1888 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1889 // virtual key area that is implemented by a separate touch panel and accidentally
1890 // triggers a virtual key.
1891 //
1892 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1893 // area and accidentally triggers a virtual key. This often happens when virtual keys
1894 // are layed out below the screen near to where the on screen keyboard's space bar
1895 // is displayed.
1896 if (mConfig.virtualKeyQuietTime > 0 &&
1897 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001898 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001899 }
1900 return false;
1901}
1902
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001903void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001904 int32_t keyEventAction, int32_t keyEventFlags) {
1905 int32_t keyCode = mCurrentVirtualKey.keyCode;
1906 int32_t scanCode = mCurrentVirtualKey.scanCode;
1907 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001908 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001909 policyFlags |= POLICY_FLAG_VIRTUAL;
1910
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001911 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1912 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1913 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001914 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001915}
1916
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001917void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001918 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1919 if (!currentIdBits.isEmpty()) {
1920 int32_t metaState = getContext()->getGlobalMetaState();
1921 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001922 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1923 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924 mCurrentCookedState.cookedPointerData.pointerProperties,
1925 mCurrentCookedState.cookedPointerData.pointerCoords,
1926 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1927 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1928 mCurrentMotionAborted = true;
1929 }
1930}
1931
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001932void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001933 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1934 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1935 int32_t metaState = getContext()->getGlobalMetaState();
1936 int32_t buttonState = mCurrentCookedState.buttonState;
1937
1938 if (currentIdBits == lastIdBits) {
1939 if (!currentIdBits.isEmpty()) {
1940 // No pointer id changes so this is a move event.
1941 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001942 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1943 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001944 mCurrentCookedState.cookedPointerData.pointerProperties,
1945 mCurrentCookedState.cookedPointerData.pointerCoords,
1946 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1947 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1948 }
1949 } else {
1950 // There may be pointers going up and pointers going down and pointers moving
1951 // all at the same time.
1952 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1953 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1954 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1955 BitSet32 dispatchedIdBits(lastIdBits.value);
1956
1957 // Update last coordinates of pointers that have moved so that we observe the new
1958 // pointer positions at the same time as other pointers that have just gone up.
1959 bool moveNeeded =
1960 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1961 mCurrentCookedState.cookedPointerData.pointerCoords,
1962 mCurrentCookedState.cookedPointerData.idToIndex,
1963 mLastCookedState.cookedPointerData.pointerProperties,
1964 mLastCookedState.cookedPointerData.pointerCoords,
1965 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1966 if (buttonState != mLastCookedState.buttonState) {
1967 moveNeeded = true;
1968 }
1969
1970 // Dispatch pointer up events.
1971 while (!upIdBits.isEmpty()) {
1972 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001973 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001974 if (isCanceled) {
1975 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1976 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001977 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001978 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001979 mLastCookedState.cookedPointerData.pointerProperties,
1980 mLastCookedState.cookedPointerData.pointerCoords,
1981 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1982 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1983 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001984 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001985 }
1986
1987 // Dispatch move events if any of the remaining pointers moved from their old locations.
1988 // Although applications receive new locations as part of individual pointer up
1989 // events, they do not generally handle them except when presented in a move event.
1990 if (moveNeeded && !moveIdBits.isEmpty()) {
1991 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001992 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1993 metaState, buttonState, 0,
1994 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001995 mCurrentCookedState.cookedPointerData.pointerCoords,
1996 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1997 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1998 }
1999
2000 // Dispatch pointer down events using the new pointer locations.
2001 while (!downIdBits.isEmpty()) {
2002 uint32_t downId = downIdBits.clearFirstMarkedBit();
2003 dispatchedIdBits.markBit(downId);
2004
2005 if (dispatchedIdBits.count() == 1) {
2006 // First pointer is going down. Set down time.
2007 mDownTime = when;
2008 }
2009
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002010 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2011 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002012 mCurrentCookedState.cookedPointerData.pointerProperties,
2013 mCurrentCookedState.cookedPointerData.pointerCoords,
2014 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
2015 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2016 }
2017 }
2018}
2019
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002020void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002021 if (mSentHoverEnter &&
2022 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2023 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2024 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002025 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2026 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002027 mLastCookedState.cookedPointerData.pointerProperties,
2028 mLastCookedState.cookedPointerData.pointerCoords,
2029 mLastCookedState.cookedPointerData.idToIndex,
2030 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2031 mOrientedYPrecision, mDownTime);
2032 mSentHoverEnter = false;
2033 }
2034}
2035
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002036void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2037 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002038 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2039 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2040 int32_t metaState = getContext()->getGlobalMetaState();
2041 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002042 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2043 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002044 mCurrentCookedState.cookedPointerData.pointerProperties,
2045 mCurrentCookedState.cookedPointerData.pointerCoords,
2046 mCurrentCookedState.cookedPointerData.idToIndex,
2047 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2048 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2049 mSentHoverEnter = true;
2050 }
2051
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002052 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2053 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002054 mCurrentCookedState.cookedPointerData.pointerProperties,
2055 mCurrentCookedState.cookedPointerData.pointerCoords,
2056 mCurrentCookedState.cookedPointerData.idToIndex,
2057 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2058 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2059 }
2060}
2061
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002062void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002063 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2064 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2065 const int32_t metaState = getContext()->getGlobalMetaState();
2066 int32_t buttonState = mLastCookedState.buttonState;
2067 while (!releasedButtons.isEmpty()) {
2068 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2069 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002070 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002071 actionButton, 0, metaState, buttonState, 0,
2072 mCurrentCookedState.cookedPointerData.pointerProperties,
2073 mCurrentCookedState.cookedPointerData.pointerCoords,
2074 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2075 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2076 }
2077}
2078
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002079void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002080 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2081 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2082 const int32_t metaState = getContext()->getGlobalMetaState();
2083 int32_t buttonState = mLastCookedState.buttonState;
2084 while (!pressedButtons.isEmpty()) {
2085 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2086 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002087 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2088 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089 mCurrentCookedState.cookedPointerData.pointerProperties,
2090 mCurrentCookedState.cookedPointerData.pointerCoords,
2091 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2092 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2093 }
2094}
2095
2096const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2097 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2098 return cookedPointerData.touchingIdBits;
2099 }
2100 return cookedPointerData.hoveringIdBits;
2101}
2102
2103void TouchInputMapper::cookPointerData() {
2104 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2105
2106 mCurrentCookedState.cookedPointerData.clear();
2107 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2108 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2109 mCurrentRawState.rawPointerData.hoveringIdBits;
2110 mCurrentCookedState.cookedPointerData.touchingIdBits =
2111 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002112 mCurrentCookedState.cookedPointerData.canceledIdBits =
2113 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002114
2115 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2116 mCurrentCookedState.buttonState = 0;
2117 } else {
2118 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2119 }
2120
2121 // Walk through the the active pointers and map device coordinates onto
2122 // surface coordinates and adjust for display orientation.
2123 for (uint32_t i = 0; i < currentPointerCount; i++) {
2124 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2125
2126 // Size
2127 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2128 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002129 case Calibration::SizeCalibration::GEOMETRIC:
2130 case Calibration::SizeCalibration::DIAMETER:
2131 case Calibration::SizeCalibration::BOX:
2132 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002133 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2134 touchMajor = in.touchMajor;
2135 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2136 toolMajor = in.toolMajor;
2137 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2138 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2139 : in.touchMajor;
2140 } else if (mRawPointerAxes.touchMajor.valid) {
2141 toolMajor = touchMajor = in.touchMajor;
2142 toolMinor = touchMinor =
2143 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2144 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2145 : in.touchMajor;
2146 } else if (mRawPointerAxes.toolMajor.valid) {
2147 touchMajor = toolMajor = in.toolMajor;
2148 touchMinor = toolMinor =
2149 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2150 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2151 : in.toolMajor;
2152 } else {
2153 ALOG_ASSERT(false,
2154 "No touch or tool axes. "
2155 "Size calibration should have been resolved to NONE.");
2156 touchMajor = 0;
2157 touchMinor = 0;
2158 toolMajor = 0;
2159 toolMinor = 0;
2160 size = 0;
2161 }
2162
2163 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2164 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2165 if (touchingCount > 1) {
2166 touchMajor /= touchingCount;
2167 touchMinor /= touchingCount;
2168 toolMajor /= touchingCount;
2169 toolMinor /= touchingCount;
2170 size /= touchingCount;
2171 }
2172 }
2173
Michael Wright227c5542020-07-02 18:30:52 +01002174 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002175 touchMajor *= mGeometricScale;
2176 touchMinor *= mGeometricScale;
2177 toolMajor *= mGeometricScale;
2178 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002179 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002180 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2181 touchMinor = touchMajor;
2182 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2183 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002184 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185 touchMinor = touchMajor;
2186 toolMinor = toolMajor;
2187 }
2188
2189 mCalibration.applySizeScaleAndBias(&touchMajor);
2190 mCalibration.applySizeScaleAndBias(&touchMinor);
2191 mCalibration.applySizeScaleAndBias(&toolMajor);
2192 mCalibration.applySizeScaleAndBias(&toolMinor);
2193 size *= mSizeScale;
2194 break;
2195 default:
2196 touchMajor = 0;
2197 touchMinor = 0;
2198 toolMajor = 0;
2199 toolMinor = 0;
2200 size = 0;
2201 break;
2202 }
2203
2204 // Pressure
2205 float pressure;
2206 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002207 case Calibration::PressureCalibration::PHYSICAL:
2208 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002209 pressure = in.pressure * mPressureScale;
2210 break;
2211 default:
2212 pressure = in.isHovering ? 0 : 1;
2213 break;
2214 }
2215
2216 // Tilt and Orientation
2217 float tilt;
2218 float orientation;
2219 if (mHaveTilt) {
2220 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2221 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2222 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2223 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2224 } else {
2225 tilt = 0;
2226
2227 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002228 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002229 orientation = in.orientation * mOrientationScale;
2230 break;
Michael Wright227c5542020-07-02 18:30:52 +01002231 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002232 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2233 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2234 if (c1 != 0 || c2 != 0) {
2235 orientation = atan2f(c1, c2) * 0.5f;
2236 float confidence = hypotf(c1, c2);
2237 float scale = 1.0f + confidence / 16.0f;
2238 touchMajor *= scale;
2239 touchMinor /= scale;
2240 toolMajor *= scale;
2241 toolMinor /= scale;
2242 } else {
2243 orientation = 0;
2244 }
2245 break;
2246 }
2247 default:
2248 orientation = 0;
2249 }
2250 }
2251
2252 // Distance
2253 float distance;
2254 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002255 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 distance = in.distance * mDistanceScale;
2257 break;
2258 default:
2259 distance = 0;
2260 }
2261
2262 // Coverage
2263 int32_t rawLeft, rawTop, rawRight, rawBottom;
2264 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002265 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002266 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2267 rawRight = in.toolMinor & 0x0000ffff;
2268 rawBottom = in.toolMajor & 0x0000ffff;
2269 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2270 break;
2271 default:
2272 rawLeft = rawTop = rawRight = rawBottom = 0;
2273 break;
2274 }
2275
2276 // Adjust X,Y coords for device calibration
2277 // TODO: Adjust coverage coords?
2278 float xTransformed = in.x, yTransformed = in.y;
2279 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002280 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002281
2282 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002283 float left, top, right, bottom;
2284
2285 switch (mSurfaceOrientation) {
2286 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002287 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2288 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2289 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2290 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2291 orientation -= M_PI_2;
2292 if (mOrientedRanges.haveOrientation &&
2293 orientation < mOrientedRanges.orientation.min) {
2294 orientation +=
2295 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2296 }
2297 break;
2298 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002299 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2300 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2301 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2302 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2303 orientation -= M_PI;
2304 if (mOrientedRanges.haveOrientation &&
2305 orientation < mOrientedRanges.orientation.min) {
2306 orientation +=
2307 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2308 }
2309 break;
2310 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002311 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2312 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2313 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2314 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2315 orientation += M_PI_2;
2316 if (mOrientedRanges.haveOrientation &&
2317 orientation > mOrientedRanges.orientation.max) {
2318 orientation -=
2319 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2320 }
2321 break;
2322 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2324 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2325 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2326 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2327 break;
2328 }
2329
2330 // Write output coords.
2331 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2332 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002333 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2334 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002335 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2336 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2337 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2338 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2339 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2340 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2341 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002342 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2344 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2345 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2346 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2347 } else {
2348 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2349 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2350 }
2351
Chris Ye364fdb52020-08-05 15:07:56 -07002352 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002353 uint32_t id = in.id;
2354 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2355 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2356 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2357 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2358 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2359 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2360 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2361 }
2362
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002363 // Write output properties.
2364 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 properties.clear();
2366 properties.id = id;
2367 properties.toolType = in.toolType;
2368
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002369 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002371 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 }
2373}
2374
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002375void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002376 PointerUsage pointerUsage) {
2377 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002378 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 mPointerUsage = pointerUsage;
2380 }
2381
2382 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002383 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002384 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 break;
Michael Wright227c5542020-07-02 18:30:52 +01002386 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002387 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 break;
Michael Wright227c5542020-07-02 18:30:52 +01002389 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002390 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 break;
Michael Wright227c5542020-07-02 18:30:52 +01002392 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393 break;
2394 }
2395}
2396
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002397void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002399 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002400 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002401 break;
Michael Wright227c5542020-07-02 18:30:52 +01002402 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002403 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 break;
Michael Wright227c5542020-07-02 18:30:52 +01002405 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002406 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002407 break;
Michael Wright227c5542020-07-02 18:30:52 +01002408 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 break;
2410 }
2411
Michael Wright227c5542020-07-02 18:30:52 +01002412 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002413}
2414
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002415void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2416 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 // Update current gesture coordinates.
2418 bool cancelPreviousGesture, finishPreviousGesture;
2419 bool sendEvents =
2420 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2421 if (!sendEvents) {
2422 return;
2423 }
2424 if (finishPreviousGesture) {
2425 cancelPreviousGesture = false;
2426 }
2427
2428 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002429 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002430 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431 if (finishPreviousGesture || cancelPreviousGesture) {
2432 mPointerController->clearSpots();
2433 }
2434
Michael Wright227c5542020-07-02 18:30:52 +01002435 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002436 setTouchSpots(mPointerGesture.currentGestureCoords,
2437 mPointerGesture.currentGestureIdToIndex,
2438 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002439 }
2440 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002441 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 }
2443
2444 // Show or hide the pointer if needed.
2445 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002446 case PointerGesture::Mode::NEUTRAL:
2447 case PointerGesture::Mode::QUIET:
2448 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2449 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002451 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452 }
2453 break;
Michael Wright227c5542020-07-02 18:30:52 +01002454 case PointerGesture::Mode::TAP:
2455 case PointerGesture::Mode::TAP_DRAG:
2456 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2457 case PointerGesture::Mode::HOVER:
2458 case PointerGesture::Mode::PRESS:
2459 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 // Unfade the pointer when the current gesture manipulates the
2461 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002462 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 break;
Michael Wright227c5542020-07-02 18:30:52 +01002464 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 // Fade the pointer when the current gesture manipulates a different
2466 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002467 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002468 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002470 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002471 }
2472 break;
2473 }
2474
2475 // Send events!
2476 int32_t metaState = getContext()->getGlobalMetaState();
2477 int32_t buttonState = mCurrentCookedState.buttonState;
2478
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002479 uint32_t flags = 0;
2480
2481 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2482 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2483 }
2484
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 // Update last coordinates of pointers that have moved so that we observe the new
2486 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002487 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2488 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2489 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2490 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2491 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2492 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002493 bool moveNeeded = false;
2494 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2495 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2496 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2497 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2498 mPointerGesture.lastGestureIdBits.value);
2499 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2500 mPointerGesture.currentGestureCoords,
2501 mPointerGesture.currentGestureIdToIndex,
2502 mPointerGesture.lastGestureProperties,
2503 mPointerGesture.lastGestureCoords,
2504 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2505 if (buttonState != mLastCookedState.buttonState) {
2506 moveNeeded = true;
2507 }
2508 }
2509
2510 // Send motion events for all pointers that went up or were canceled.
2511 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2512 if (!dispatchedGestureIdBits.isEmpty()) {
2513 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002514 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2515 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2517 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2518 mPointerGesture.downTime);
2519
2520 dispatchedGestureIdBits.clear();
2521 } else {
2522 BitSet32 upGestureIdBits;
2523 if (finishPreviousGesture) {
2524 upGestureIdBits = dispatchedGestureIdBits;
2525 } else {
2526 upGestureIdBits.value =
2527 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2528 }
2529 while (!upGestureIdBits.isEmpty()) {
2530 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2531
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002532 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002533 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002534 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535 mPointerGesture.lastGestureCoords,
2536 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2537 0, mPointerGesture.downTime);
2538
2539 dispatchedGestureIdBits.clearBit(id);
2540 }
2541 }
2542 }
2543
2544 // Send motion events for all pointers that moved.
2545 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002546 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002547 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002548 mPointerGesture.currentGestureProperties,
2549 mPointerGesture.currentGestureCoords,
2550 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2551 mPointerGesture.downTime);
2552 }
2553
2554 // Send motion events for all pointers that went down.
2555 if (down) {
2556 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2557 ~dispatchedGestureIdBits.value);
2558 while (!downGestureIdBits.isEmpty()) {
2559 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2560 dispatchedGestureIdBits.markBit(id);
2561
2562 if (dispatchedGestureIdBits.count() == 1) {
2563 mPointerGesture.downTime = when;
2564 }
2565
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002566 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002567 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002568 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002569 mPointerGesture.currentGestureCoords,
2570 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2571 0, mPointerGesture.downTime);
2572 }
2573 }
2574
2575 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002576 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002577 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2578 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002579 mPointerGesture.currentGestureProperties,
2580 mPointerGesture.currentGestureCoords,
2581 mPointerGesture.currentGestureIdToIndex,
2582 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2583 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2584 // Synthesize a hover move event after all pointers go up to indicate that
2585 // the pointer is hovering again even if the user is not currently touching
2586 // the touch pad. This ensures that a view will receive a fresh hover enter
2587 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002588 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002589
2590 PointerProperties pointerProperties;
2591 pointerProperties.clear();
2592 pointerProperties.id = 0;
2593 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2594
2595 PointerCoords pointerCoords;
2596 pointerCoords.clear();
2597 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2598 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2599
2600 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002601 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002602 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002603 metaState, buttonState, MotionClassification::NONE,
2604 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2605 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002606 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002607 }
2608
2609 // Update state.
2610 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2611 if (!down) {
2612 mPointerGesture.lastGestureIdBits.clear();
2613 } else {
2614 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2615 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2616 uint32_t id = idBits.clearFirstMarkedBit();
2617 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2618 mPointerGesture.lastGestureProperties[index].copyFrom(
2619 mPointerGesture.currentGestureProperties[index]);
2620 mPointerGesture.lastGestureCoords[index].copyFrom(
2621 mPointerGesture.currentGestureCoords[index]);
2622 mPointerGesture.lastGestureIdToIndex[id] = index;
2623 }
2624 }
2625}
2626
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002627void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002628 // Cancel previously dispatches pointers.
2629 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2630 int32_t metaState = getContext()->getGlobalMetaState();
2631 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002632 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2633 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002634 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2635 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2636 0, 0, mPointerGesture.downTime);
2637 }
2638
2639 // Reset the current pointer gesture.
2640 mPointerGesture.reset();
2641 mPointerVelocityControl.reset();
2642
2643 // Remove any current spots.
2644 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002645 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002646 mPointerController->clearSpots();
2647 }
2648}
2649
2650bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2651 bool* outFinishPreviousGesture, bool isTimeout) {
2652 *outCancelPreviousGesture = false;
2653 *outFinishPreviousGesture = false;
2654
2655 // Handle TAP timeout.
2656 if (isTimeout) {
2657#if DEBUG_GESTURES
2658 ALOGD("Gestures: Processing timeout");
2659#endif
2660
Michael Wright227c5542020-07-02 18:30:52 +01002661 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002662 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2663 // The tap/drag timeout has not yet expired.
2664 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2665 mConfig.pointerGestureTapDragInterval);
2666 } else {
2667 // The tap is finished.
2668#if DEBUG_GESTURES
2669 ALOGD("Gestures: TAP finished");
2670#endif
2671 *outFinishPreviousGesture = true;
2672
2673 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002674 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002675 mPointerGesture.currentGestureIdBits.clear();
2676
2677 mPointerVelocityControl.reset();
2678 return true;
2679 }
2680 }
2681
2682 // We did not handle this timeout.
2683 return false;
2684 }
2685
2686 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2687 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2688
2689 // Update the velocity tracker.
2690 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002691 std::vector<VelocityTracker::Position> positions;
2692 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002693 uint32_t id = idBits.clearFirstMarkedBit();
2694 const RawPointerData::Pointer& pointer =
2695 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002696 float x = pointer.x * mPointerXMovementScale;
2697 float y = pointer.y * mPointerYMovementScale;
2698 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002699 }
2700 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2701 positions);
2702 }
2703
2704 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2705 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002706 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2707 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2708 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002709 mPointerGesture.resetTap();
2710 }
2711
2712 // Pick a new active touch id if needed.
2713 // Choose an arbitrary pointer that just went down, if there is one.
2714 // Otherwise choose an arbitrary remaining pointer.
2715 // This guarantees we always have an active touch id when there is at least one pointer.
2716 // We keep the same active touch id for as long as possible.
2717 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2718 int32_t activeTouchId = lastActiveTouchId;
2719 if (activeTouchId < 0) {
2720 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2721 activeTouchId = mPointerGesture.activeTouchId =
2722 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2723 mPointerGesture.firstTouchTime = when;
2724 }
2725 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2726 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2727 activeTouchId = mPointerGesture.activeTouchId =
2728 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2729 } else {
2730 activeTouchId = mPointerGesture.activeTouchId = -1;
2731 }
2732 }
2733
2734 // Determine whether we are in quiet time.
2735 bool isQuietTime = false;
2736 if (activeTouchId < 0) {
2737 mPointerGesture.resetQuietTime();
2738 } else {
2739 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2740 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002741 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2742 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2743 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002744 currentFingerCount < 2) {
2745 // Enter quiet time when exiting swipe or freeform state.
2746 // This is to prevent accidentally entering the hover state and flinging the
2747 // pointer when finishing a swipe and there is still one pointer left onscreen.
2748 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002749 } else if (mPointerGesture.lastGestureMode ==
2750 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002751 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2752 // Enter quiet time when releasing the button and there are still two or more
2753 // fingers down. This may indicate that one finger was used to press the button
2754 // but it has not gone up yet.
2755 isQuietTime = true;
2756 }
2757 if (isQuietTime) {
2758 mPointerGesture.quietTime = when;
2759 }
2760 }
2761 }
2762
2763 // Switch states based on button and pointer state.
2764 if (isQuietTime) {
2765 // Case 1: Quiet time. (QUIET)
2766#if DEBUG_GESTURES
2767 ALOGD("Gestures: QUIET for next %0.3fms",
2768 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2769#endif
Michael Wright227c5542020-07-02 18:30:52 +01002770 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002771 *outFinishPreviousGesture = true;
2772 }
2773
2774 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002775 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002776 mPointerGesture.currentGestureIdBits.clear();
2777
2778 mPointerVelocityControl.reset();
2779 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2780 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2781 // The pointer follows the active touch point.
2782 // Emit DOWN, MOVE, UP events at the pointer location.
2783 //
2784 // Only the active touch matters; other fingers are ignored. This policy helps
2785 // to handle the case where the user places a second finger on the touch pad
2786 // to apply the necessary force to depress an integrated button below the surface.
2787 // We don't want the second finger to be delivered to applications.
2788 //
2789 // For this to work well, we need to make sure to track the pointer that is really
2790 // active. If the user first puts one finger down to click then adds another
2791 // finger to drag then the active pointer should switch to the finger that is
2792 // being dragged.
2793#if DEBUG_GESTURES
2794 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2795 "currentFingerCount=%d",
2796 activeTouchId, currentFingerCount);
2797#endif
2798 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002799 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002800 *outFinishPreviousGesture = true;
2801 mPointerGesture.activeGestureId = 0;
2802 }
2803
2804 // Switch pointers if needed.
2805 // Find the fastest pointer and follow it.
2806 if (activeTouchId >= 0 && currentFingerCount > 1) {
2807 int32_t bestId = -1;
2808 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2809 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2810 uint32_t id = idBits.clearFirstMarkedBit();
2811 float vx, vy;
2812 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2813 float speed = hypotf(vx, vy);
2814 if (speed > bestSpeed) {
2815 bestId = id;
2816 bestSpeed = speed;
2817 }
2818 }
2819 }
2820 if (bestId >= 0 && bestId != activeTouchId) {
2821 mPointerGesture.activeTouchId = activeTouchId = bestId;
2822#if DEBUG_GESTURES
2823 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2824 "bestId=%d, bestSpeed=%0.3f",
2825 bestId, bestSpeed);
2826#endif
2827 }
2828 }
2829
2830 float deltaX = 0, deltaY = 0;
2831 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2832 const RawPointerData::Pointer& currentPointer =
2833 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2834 const RawPointerData::Pointer& lastPointer =
2835 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2836 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2837 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2838
2839 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2840 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2841
2842 // Move the pointer using a relative motion.
2843 // When using spots, the click will occur at the position of the anchor
2844 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002845 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002846 } else {
2847 mPointerVelocityControl.reset();
2848 }
2849
Prabir Pradhand7482e72021-03-09 13:54:55 -08002850 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002851
Michael Wright227c5542020-07-02 18:30:52 +01002852 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002853 mPointerGesture.currentGestureIdBits.clear();
2854 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2855 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2856 mPointerGesture.currentGestureProperties[0].clear();
2857 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2858 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2859 mPointerGesture.currentGestureCoords[0].clear();
2860 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2861 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2862 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2863 } else if (currentFingerCount == 0) {
2864 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002865 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002866 *outFinishPreviousGesture = true;
2867 }
2868
2869 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2870 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2871 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002872 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2873 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002874 lastFingerCount == 1) {
2875 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002876 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002877 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2878 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2879#if DEBUG_GESTURES
2880 ALOGD("Gestures: TAP");
2881#endif
2882
2883 mPointerGesture.tapUpTime = when;
2884 getContext()->requestTimeoutAtTime(when +
2885 mConfig.pointerGestureTapDragInterval);
2886
2887 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002888 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002889 mPointerGesture.currentGestureIdBits.clear();
2890 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2891 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2892 mPointerGesture.currentGestureProperties[0].clear();
2893 mPointerGesture.currentGestureProperties[0].id =
2894 mPointerGesture.activeGestureId;
2895 mPointerGesture.currentGestureProperties[0].toolType =
2896 AMOTION_EVENT_TOOL_TYPE_FINGER;
2897 mPointerGesture.currentGestureCoords[0].clear();
2898 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2899 mPointerGesture.tapX);
2900 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2901 mPointerGesture.tapY);
2902 mPointerGesture.currentGestureCoords[0]
2903 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2904
2905 tapped = true;
2906 } else {
2907#if DEBUG_GESTURES
2908 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2909 y - mPointerGesture.tapY);
2910#endif
2911 }
2912 } else {
2913#if DEBUG_GESTURES
2914 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2915 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2916 (when - mPointerGesture.tapDownTime) * 0.000001f);
2917 } else {
2918 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2919 }
2920#endif
2921 }
2922 }
2923
2924 mPointerVelocityControl.reset();
2925
2926 if (!tapped) {
2927#if DEBUG_GESTURES
2928 ALOGD("Gestures: NEUTRAL");
2929#endif
2930 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002931 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002932 mPointerGesture.currentGestureIdBits.clear();
2933 }
2934 } else if (currentFingerCount == 1) {
2935 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2936 // The pointer follows the active touch point.
2937 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2938 // When in TAP_DRAG, emit MOVE events at the pointer location.
2939 ALOG_ASSERT(activeTouchId >= 0);
2940
Michael Wright227c5542020-07-02 18:30:52 +01002941 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2942 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002944 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2946 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002947 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002948 } else {
2949#if DEBUG_GESTURES
2950 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2951 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2952#endif
2953 }
2954 } else {
2955#if DEBUG_GESTURES
2956 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2957 (when - mPointerGesture.tapUpTime) * 0.000001f);
2958#endif
2959 }
Michael Wright227c5542020-07-02 18:30:52 +01002960 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2961 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002962 }
2963
2964 float deltaX = 0, deltaY = 0;
2965 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2966 const RawPointerData::Pointer& currentPointer =
2967 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2968 const RawPointerData::Pointer& lastPointer =
2969 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2970 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2971 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2972
2973 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2974 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2975
2976 // Move the pointer using a relative motion.
2977 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002978 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979 } else {
2980 mPointerVelocityControl.reset();
2981 }
2982
2983 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002984 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002985#if DEBUG_GESTURES
2986 ALOGD("Gestures: TAP_DRAG");
2987#endif
2988 down = true;
2989 } else {
2990#if DEBUG_GESTURES
2991 ALOGD("Gestures: HOVER");
2992#endif
Michael Wright227c5542020-07-02 18:30:52 +01002993 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002994 *outFinishPreviousGesture = true;
2995 }
2996 mPointerGesture.activeGestureId = 0;
2997 down = false;
2998 }
2999
Prabir Pradhand7482e72021-03-09 13:54:55 -08003000 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003001
3002 mPointerGesture.currentGestureIdBits.clear();
3003 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3004 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3005 mPointerGesture.currentGestureProperties[0].clear();
3006 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3007 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3008 mPointerGesture.currentGestureCoords[0].clear();
3009 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3010 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3011 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3012 down ? 1.0f : 0.0f);
3013
3014 if (lastFingerCount == 0 && currentFingerCount != 0) {
3015 mPointerGesture.resetTap();
3016 mPointerGesture.tapDownTime = when;
3017 mPointerGesture.tapX = x;
3018 mPointerGesture.tapY = y;
3019 }
3020 } else {
3021 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3022 // We need to provide feedback for each finger that goes down so we cannot wait
3023 // for the fingers to move before deciding what to do.
3024 //
3025 // The ambiguous case is deciding what to do when there are two fingers down but they
3026 // have not moved enough to determine whether they are part of a drag or part of a
3027 // freeform gesture, or just a press or long-press at the pointer location.
3028 //
3029 // When there are two fingers we start with the PRESS hypothesis and we generate a
3030 // down at the pointer location.
3031 //
3032 // When the two fingers move enough or when additional fingers are added, we make
3033 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3034 ALOG_ASSERT(activeTouchId >= 0);
3035
3036 bool settled = when >=
3037 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003038 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3039 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3040 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003041 *outFinishPreviousGesture = true;
3042 } else if (!settled && currentFingerCount > lastFingerCount) {
3043 // Additional pointers have gone down but not yet settled.
3044 // Reset the gesture.
3045#if DEBUG_GESTURES
3046 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3047 "settle time remaining %0.3fms",
3048 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3049 when) * 0.000001f);
3050#endif
3051 *outCancelPreviousGesture = true;
3052 } else {
3053 // Continue previous gesture.
3054 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3055 }
3056
3057 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003058 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003059 mPointerGesture.activeGestureId = 0;
3060 mPointerGesture.referenceIdBits.clear();
3061 mPointerVelocityControl.reset();
3062
3063 // Use the centroid and pointer location as the reference points for the gesture.
3064#if DEBUG_GESTURES
3065 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3066 "settle time remaining %0.3fms",
3067 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3068 when) * 0.000001f);
3069#endif
3070 mCurrentRawState.rawPointerData
3071 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3072 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003073 auto [x, y] = getMouseCursorPosition();
3074 mPointerGesture.referenceGestureX = x;
3075 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003076 }
3077
3078 // Clear the reference deltas for fingers not yet included in the reference calculation.
3079 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3080 ~mPointerGesture.referenceIdBits.value);
3081 !idBits.isEmpty();) {
3082 uint32_t id = idBits.clearFirstMarkedBit();
3083 mPointerGesture.referenceDeltas[id].dx = 0;
3084 mPointerGesture.referenceDeltas[id].dy = 0;
3085 }
3086 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3087
3088 // Add delta for all fingers and calculate a common movement delta.
3089 float commonDeltaX = 0, commonDeltaY = 0;
3090 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3091 mCurrentCookedState.fingerIdBits.value);
3092 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3093 bool first = (idBits == commonIdBits);
3094 uint32_t id = idBits.clearFirstMarkedBit();
3095 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3096 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3097 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3098 delta.dx += cpd.x - lpd.x;
3099 delta.dy += cpd.y - lpd.y;
3100
3101 if (first) {
3102 commonDeltaX = delta.dx;
3103 commonDeltaY = delta.dy;
3104 } else {
3105 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3106 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3107 }
3108 }
3109
3110 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003111 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003112 float dist[MAX_POINTER_ID + 1];
3113 int32_t distOverThreshold = 0;
3114 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3115 uint32_t id = idBits.clearFirstMarkedBit();
3116 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3117 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3118 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3119 distOverThreshold += 1;
3120 }
3121 }
3122
3123 // Only transition when at least two pointers have moved further than
3124 // the minimum distance threshold.
3125 if (distOverThreshold >= 2) {
3126 if (currentFingerCount > 2) {
3127 // There are more than two pointers, switch to FREEFORM.
3128#if DEBUG_GESTURES
3129 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3130 currentFingerCount);
3131#endif
3132 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003133 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003134 } else {
3135 // There are exactly two pointers.
3136 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3137 uint32_t id1 = idBits.clearFirstMarkedBit();
3138 uint32_t id2 = idBits.firstMarkedBit();
3139 const RawPointerData::Pointer& p1 =
3140 mCurrentRawState.rawPointerData.pointerForId(id1);
3141 const RawPointerData::Pointer& p2 =
3142 mCurrentRawState.rawPointerData.pointerForId(id2);
3143 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3144 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3145 // There are two pointers but they are too far apart for a SWIPE,
3146 // switch to FREEFORM.
3147#if DEBUG_GESTURES
3148 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3149 mutualDistance, mPointerGestureMaxSwipeWidth);
3150#endif
3151 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003152 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003153 } else {
3154 // There are two pointers. Wait for both pointers to start moving
3155 // before deciding whether this is a SWIPE or FREEFORM gesture.
3156 float dist1 = dist[id1];
3157 float dist2 = dist[id2];
3158 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3159 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3160 // Calculate the dot product of the displacement vectors.
3161 // When the vectors are oriented in approximately the same direction,
3162 // the angle betweeen them is near zero and the cosine of the angle
3163 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3164 // mag(v2).
3165 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3166 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3167 float dx1 = delta1.dx * mPointerXZoomScale;
3168 float dy1 = delta1.dy * mPointerYZoomScale;
3169 float dx2 = delta2.dx * mPointerXZoomScale;
3170 float dy2 = delta2.dy * mPointerYZoomScale;
3171 float dot = dx1 * dx2 + dy1 * dy2;
3172 float cosine = dot / (dist1 * dist2); // denominator always > 0
3173 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3174 // Pointers are moving in the same direction. Switch to SWIPE.
3175#if DEBUG_GESTURES
3176 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3177 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3178 "cosine %0.3f >= %0.3f",
3179 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3180 mConfig.pointerGestureMultitouchMinDistance, cosine,
3181 mConfig.pointerGestureSwipeTransitionAngleCosine);
3182#endif
Michael Wright227c5542020-07-02 18:30:52 +01003183 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003184 } else {
3185 // Pointers are moving in different directions. Switch to FREEFORM.
3186#if DEBUG_GESTURES
3187 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3188 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3189 "cosine %0.3f < %0.3f",
3190 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3191 mConfig.pointerGestureMultitouchMinDistance, cosine,
3192 mConfig.pointerGestureSwipeTransitionAngleCosine);
3193#endif
3194 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003195 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003196 }
3197 }
3198 }
3199 }
3200 }
Michael Wright227c5542020-07-02 18:30:52 +01003201 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003202 // Switch from SWIPE to FREEFORM if additional pointers go down.
3203 // Cancel previous gesture.
3204 if (currentFingerCount > 2) {
3205#if DEBUG_GESTURES
3206 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3207 currentFingerCount);
3208#endif
3209 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003210 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003211 }
3212 }
3213
3214 // Move the reference points based on the overall group motion of the fingers
3215 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003216 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003217 (commonDeltaX || commonDeltaY)) {
3218 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3219 uint32_t id = idBits.clearFirstMarkedBit();
3220 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3221 delta.dx = 0;
3222 delta.dy = 0;
3223 }
3224
3225 mPointerGesture.referenceTouchX += commonDeltaX;
3226 mPointerGesture.referenceTouchY += commonDeltaY;
3227
3228 commonDeltaX *= mPointerXMovementScale;
3229 commonDeltaY *= mPointerYMovementScale;
3230
3231 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3232 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3233
3234 mPointerGesture.referenceGestureX += commonDeltaX;
3235 mPointerGesture.referenceGestureY += commonDeltaY;
3236 }
3237
3238 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003239 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3240 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003241 // PRESS or SWIPE mode.
3242#if DEBUG_GESTURES
3243 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3244 "activeGestureId=%d, currentTouchPointerCount=%d",
3245 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3246#endif
3247 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3248
3249 mPointerGesture.currentGestureIdBits.clear();
3250 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3251 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3252 mPointerGesture.currentGestureProperties[0].clear();
3253 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3254 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3255 mPointerGesture.currentGestureCoords[0].clear();
3256 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3257 mPointerGesture.referenceGestureX);
3258 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3259 mPointerGesture.referenceGestureY);
3260 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003261 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003262 // FREEFORM mode.
3263#if DEBUG_GESTURES
3264 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3265 "activeGestureId=%d, currentTouchPointerCount=%d",
3266 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3267#endif
3268 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3269
3270 mPointerGesture.currentGestureIdBits.clear();
3271
3272 BitSet32 mappedTouchIdBits;
3273 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003274 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003275 // Initially, assign the active gesture id to the active touch point
3276 // if there is one. No other touch id bits are mapped yet.
3277 if (!*outCancelPreviousGesture) {
3278 mappedTouchIdBits.markBit(activeTouchId);
3279 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3280 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3281 mPointerGesture.activeGestureId;
3282 } else {
3283 mPointerGesture.activeGestureId = -1;
3284 }
3285 } else {
3286 // Otherwise, assume we mapped all touches from the previous frame.
3287 // Reuse all mappings that are still applicable.
3288 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3289 mCurrentCookedState.fingerIdBits.value;
3290 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3291
3292 // Check whether we need to choose a new active gesture id because the
3293 // current went went up.
3294 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3295 ~mCurrentCookedState.fingerIdBits.value);
3296 !upTouchIdBits.isEmpty();) {
3297 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3298 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3299 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3300 mPointerGesture.activeGestureId = -1;
3301 break;
3302 }
3303 }
3304 }
3305
3306#if DEBUG_GESTURES
3307 ALOGD("Gestures: FREEFORM follow up "
3308 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3309 "activeGestureId=%d",
3310 mappedTouchIdBits.value, usedGestureIdBits.value,
3311 mPointerGesture.activeGestureId);
3312#endif
3313
3314 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3315 for (uint32_t i = 0; i < currentFingerCount; i++) {
3316 uint32_t touchId = idBits.clearFirstMarkedBit();
3317 uint32_t gestureId;
3318 if (!mappedTouchIdBits.hasBit(touchId)) {
3319 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3320 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3321#if DEBUG_GESTURES
3322 ALOGD("Gestures: FREEFORM "
3323 "new mapping for touch id %d -> gesture id %d",
3324 touchId, gestureId);
3325#endif
3326 } else {
3327 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3328#if DEBUG_GESTURES
3329 ALOGD("Gestures: FREEFORM "
3330 "existing mapping for touch id %d -> gesture id %d",
3331 touchId, gestureId);
3332#endif
3333 }
3334 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3335 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3336
3337 const RawPointerData::Pointer& pointer =
3338 mCurrentRawState.rawPointerData.pointerForId(touchId);
3339 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3340 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3341 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3342
3343 mPointerGesture.currentGestureProperties[i].clear();
3344 mPointerGesture.currentGestureProperties[i].id = gestureId;
3345 mPointerGesture.currentGestureProperties[i].toolType =
3346 AMOTION_EVENT_TOOL_TYPE_FINGER;
3347 mPointerGesture.currentGestureCoords[i].clear();
3348 mPointerGesture.currentGestureCoords[i]
3349 .setAxisValue(AMOTION_EVENT_AXIS_X,
3350 mPointerGesture.referenceGestureX + deltaX);
3351 mPointerGesture.currentGestureCoords[i]
3352 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3353 mPointerGesture.referenceGestureY + deltaY);
3354 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3355 1.0f);
3356 }
3357
3358 if (mPointerGesture.activeGestureId < 0) {
3359 mPointerGesture.activeGestureId =
3360 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3361#if DEBUG_GESTURES
3362 ALOGD("Gestures: FREEFORM new "
3363 "activeGestureId=%d",
3364 mPointerGesture.activeGestureId);
3365#endif
3366 }
3367 }
3368 }
3369
3370 mPointerController->setButtonState(mCurrentRawState.buttonState);
3371
3372#if DEBUG_GESTURES
3373 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3374 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3375 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3376 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3377 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3378 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3379 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3380 uint32_t id = idBits.clearFirstMarkedBit();
3381 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3382 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3383 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3384 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3385 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3386 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3387 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3388 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3389 }
3390 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3391 uint32_t id = idBits.clearFirstMarkedBit();
3392 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3393 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3394 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3395 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3396 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3397 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3398 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3399 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3400 }
3401#endif
3402 return true;
3403}
3404
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003405void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003406 mPointerSimple.currentCoords.clear();
3407 mPointerSimple.currentProperties.clear();
3408
3409 bool down, hovering;
3410 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3411 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3412 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003413 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3414 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003415
3416 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3417 down = !hovering;
3418
Prabir Pradhand7482e72021-03-09 13:54:55 -08003419 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003420 mPointerSimple.currentCoords.copyFrom(
3421 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3422 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3423 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3424 mPointerSimple.currentProperties.id = 0;
3425 mPointerSimple.currentProperties.toolType =
3426 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3427 } else {
3428 down = false;
3429 hovering = false;
3430 }
3431
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003432 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003433}
3434
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003435void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3436 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003437}
3438
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003439void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003440 mPointerSimple.currentCoords.clear();
3441 mPointerSimple.currentProperties.clear();
3442
3443 bool down, hovering;
3444 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3445 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3446 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3447 float deltaX = 0, deltaY = 0;
3448 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3449 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3450 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3451 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3452 mPointerXMovementScale;
3453 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3454 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3455 mPointerYMovementScale;
3456
3457 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3458 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3459
Prabir Pradhand7482e72021-03-09 13:54:55 -08003460 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003461 } else {
3462 mPointerVelocityControl.reset();
3463 }
3464
3465 down = isPointerDown(mCurrentRawState.buttonState);
3466 hovering = !down;
3467
Prabir Pradhand7482e72021-03-09 13:54:55 -08003468 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469 mPointerSimple.currentCoords.copyFrom(
3470 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3471 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3472 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3473 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3474 hovering ? 0.0f : 1.0f);
3475 mPointerSimple.currentProperties.id = 0;
3476 mPointerSimple.currentProperties.toolType =
3477 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3478 } else {
3479 mPointerVelocityControl.reset();
3480
3481 down = false;
3482 hovering = false;
3483 }
3484
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003485 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003486}
3487
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003488void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3489 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003490
3491 mPointerVelocityControl.reset();
3492}
3493
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003494void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3495 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003496 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003497
3498 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003499 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003500 mPointerController->clearSpots();
3501 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003502 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003503 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003504 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003505 }
Garfield Tan9514d782020-11-10 16:37:23 -08003506 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003507
Prabir Pradhand7482e72021-03-09 13:54:55 -08003508 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509
3510 if (mPointerSimple.down && !down) {
3511 mPointerSimple.down = false;
3512
3513 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003514 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3515 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003516 mLastRawState.buttonState, MotionClassification::NONE,
3517 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3518 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3519 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3520 /* videoFrames */ {});
3521 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003522 }
3523
3524 if (mPointerSimple.hovering && !hovering) {
3525 mPointerSimple.hovering = false;
3526
3527 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003528 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3529 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3530 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003531 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3532 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3533 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3534 /* videoFrames */ {});
3535 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003536 }
3537
3538 if (down) {
3539 if (!mPointerSimple.down) {
3540 mPointerSimple.down = true;
3541 mPointerSimple.downTime = when;
3542
3543 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003544 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003545 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3546 metaState, mCurrentRawState.buttonState,
3547 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3548 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3549 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3550 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3551 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003552 }
3553
3554 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003555 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3556 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003557 mCurrentRawState.buttonState, MotionClassification::NONE,
3558 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3559 &mPointerSimple.currentCoords, mOrientedXPrecision,
3560 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3561 mPointerSimple.downTime, /* videoFrames */ {});
3562 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 }
3564
3565 if (hovering) {
3566 if (!mPointerSimple.hovering) {
3567 mPointerSimple.hovering = true;
3568
3569 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003570 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003571 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3572 metaState, mCurrentRawState.buttonState,
3573 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3574 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3575 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3576 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3577 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003578 }
3579
3580 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003581 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3582 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3583 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003584 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3585 &mPointerSimple.currentCoords, mOrientedXPrecision,
3586 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3587 mPointerSimple.downTime, /* videoFrames */ {});
3588 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589 }
3590
3591 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3592 float vscroll = mCurrentRawState.rawVScroll;
3593 float hscroll = mCurrentRawState.rawHScroll;
3594 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3595 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3596
3597 // Send scroll.
3598 PointerCoords pointerCoords;
3599 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3600 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3601 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3602
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003603 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3604 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003605 mCurrentRawState.buttonState, MotionClassification::NONE,
3606 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3607 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3608 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3609 /* videoFrames */ {});
3610 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003611 }
3612
3613 // Save state.
3614 if (down || hovering) {
3615 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3616 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3617 } else {
3618 mPointerSimple.reset();
3619 }
3620}
3621
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003622void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003623 mPointerSimple.currentCoords.clear();
3624 mPointerSimple.currentProperties.clear();
3625
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003626 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003627}
3628
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003629void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3630 uint32_t source, int32_t action, int32_t actionButton,
3631 int32_t flags, int32_t metaState, int32_t buttonState,
3632 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003633 const PointerCoords* coords, const uint32_t* idToIndex,
3634 BitSet32 idBits, int32_t changedId, float xPrecision,
3635 float yPrecision, nsecs_t downTime) {
3636 PointerCoords pointerCoords[MAX_POINTERS];
3637 PointerProperties pointerProperties[MAX_POINTERS];
3638 uint32_t pointerCount = 0;
3639 while (!idBits.isEmpty()) {
3640 uint32_t id = idBits.clearFirstMarkedBit();
3641 uint32_t index = idToIndex[id];
3642 pointerProperties[pointerCount].copyFrom(properties[index]);
3643 pointerCoords[pointerCount].copyFrom(coords[index]);
3644
3645 if (changedId >= 0 && id == uint32_t(changedId)) {
3646 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3647 }
3648
3649 pointerCount += 1;
3650 }
3651
3652 ALOG_ASSERT(pointerCount != 0);
3653
3654 if (changedId >= 0 && pointerCount == 1) {
3655 // Replace initial down and final up action.
3656 // We can compare the action without masking off the changed pointer index
3657 // because we know the index is 0.
3658 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3659 action = AMOTION_EVENT_ACTION_DOWN;
3660 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003661 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3662 action = AMOTION_EVENT_ACTION_CANCEL;
3663 } else {
3664 action = AMOTION_EVENT_ACTION_UP;
3665 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003666 } else {
3667 // Can't happen.
3668 ALOG_ASSERT(false);
3669 }
3670 }
3671 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3672 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003673 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003674 auto [x, y] = getMouseCursorPosition();
3675 xCursorPosition = x;
3676 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003677 }
3678 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3679 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003680 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003681 std::for_each(frames.begin(), frames.end(),
3682 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003683 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3684 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003685 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3686 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3687 downTime, std::move(frames));
3688 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003689}
3690
3691bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3692 const PointerCoords* inCoords,
3693 const uint32_t* inIdToIndex,
3694 PointerProperties* outProperties,
3695 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3696 BitSet32 idBits) const {
3697 bool changed = false;
3698 while (!idBits.isEmpty()) {
3699 uint32_t id = idBits.clearFirstMarkedBit();
3700 uint32_t inIndex = inIdToIndex[id];
3701 uint32_t outIndex = outIdToIndex[id];
3702
3703 const PointerProperties& curInProperties = inProperties[inIndex];
3704 const PointerCoords& curInCoords = inCoords[inIndex];
3705 PointerProperties& curOutProperties = outProperties[outIndex];
3706 PointerCoords& curOutCoords = outCoords[outIndex];
3707
3708 if (curInProperties != curOutProperties) {
3709 curOutProperties.copyFrom(curInProperties);
3710 changed = true;
3711 }
3712
3713 if (curInCoords != curOutCoords) {
3714 curOutCoords.copyFrom(curInCoords);
3715 changed = true;
3716 }
3717 }
3718 return changed;
3719}
3720
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003721void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3722 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3723 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003724}
3725
Arthur Hung4197f6b2020-03-16 15:39:59 +08003726// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003727void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003728 // Scale to surface coordinate.
3729 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3730 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3731
arthurhunga36b28e2020-12-29 20:28:15 +08003732 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3733 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3734
Arthur Hung4197f6b2020-03-16 15:39:59 +08003735 // Rotate to surface coordinate.
3736 // 0 - no swap and reverse.
3737 // 90 - swap x/y and reverse y.
3738 // 180 - reverse x, y.
3739 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003740 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003741 case DISPLAY_ORIENTATION_0:
3742 x = xScaled + mXTranslate;
3743 y = yScaled + mYTranslate;
3744 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003745 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003746 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003747 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003748 break;
3749 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003750 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3751 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003752 break;
3753 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003754 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003755 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003756 break;
3757 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003758 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003759 }
3760}
3761
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003762bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003763 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3764 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3765
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003766 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003767 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003768 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003769 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003770}
3771
3772const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3773 for (const VirtualKey& virtualKey : mVirtualKeys) {
3774#if DEBUG_VIRTUAL_KEYS
3775 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3776 "left=%d, top=%d, right=%d, bottom=%d",
3777 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3778 virtualKey.hitRight, virtualKey.hitBottom);
3779#endif
3780
3781 if (virtualKey.isHit(x, y)) {
3782 return &virtualKey;
3783 }
3784 }
3785
3786 return nullptr;
3787}
3788
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003789void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3790 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3791 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003792
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003793 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003794
3795 if (currentPointerCount == 0) {
3796 // No pointers to assign.
3797 return;
3798 }
3799
3800 if (lastPointerCount == 0) {
3801 // All pointers are new.
3802 for (uint32_t i = 0; i < currentPointerCount; i++) {
3803 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003804 current.rawPointerData.pointers[i].id = id;
3805 current.rawPointerData.idToIndex[id] = i;
3806 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003807 }
3808 return;
3809 }
3810
3811 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003812 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003813 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003814 uint32_t id = last.rawPointerData.pointers[0].id;
3815 current.rawPointerData.pointers[0].id = id;
3816 current.rawPointerData.idToIndex[id] = 0;
3817 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003818 return;
3819 }
3820
3821 // General case.
3822 // We build a heap of squared euclidean distances between current and last pointers
3823 // associated with the current and last pointer indices. Then, we find the best
3824 // match (by distance) for each current pointer.
3825 // The pointers must have the same tool type but it is possible for them to
3826 // transition from hovering to touching or vice-versa while retaining the same id.
3827 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3828
3829 uint32_t heapSize = 0;
3830 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3831 currentPointerIndex++) {
3832 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3833 lastPointerIndex++) {
3834 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003835 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003836 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003837 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003838 if (currentPointer.toolType == lastPointer.toolType) {
3839 int64_t deltaX = currentPointer.x - lastPointer.x;
3840 int64_t deltaY = currentPointer.y - lastPointer.y;
3841
3842 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3843
3844 // Insert new element into the heap (sift up).
3845 heap[heapSize].currentPointerIndex = currentPointerIndex;
3846 heap[heapSize].lastPointerIndex = lastPointerIndex;
3847 heap[heapSize].distance = distance;
3848 heapSize += 1;
3849 }
3850 }
3851 }
3852
3853 // Heapify
3854 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3855 startIndex -= 1;
3856 for (uint32_t parentIndex = startIndex;;) {
3857 uint32_t childIndex = parentIndex * 2 + 1;
3858 if (childIndex >= heapSize) {
3859 break;
3860 }
3861
3862 if (childIndex + 1 < heapSize &&
3863 heap[childIndex + 1].distance < heap[childIndex].distance) {
3864 childIndex += 1;
3865 }
3866
3867 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3868 break;
3869 }
3870
3871 swap(heap[parentIndex], heap[childIndex]);
3872 parentIndex = childIndex;
3873 }
3874 }
3875
3876#if DEBUG_POINTER_ASSIGNMENT
3877 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3878 for (size_t i = 0; i < heapSize; i++) {
3879 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3880 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3881 }
3882#endif
3883
3884 // Pull matches out by increasing order of distance.
3885 // To avoid reassigning pointers that have already been matched, the loop keeps track
3886 // of which last and current pointers have been matched using the matchedXXXBits variables.
3887 // It also tracks the used pointer id bits.
3888 BitSet32 matchedLastBits(0);
3889 BitSet32 matchedCurrentBits(0);
3890 BitSet32 usedIdBits(0);
3891 bool first = true;
3892 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3893 while (heapSize > 0) {
3894 if (first) {
3895 // The first time through the loop, we just consume the root element of
3896 // the heap (the one with smallest distance).
3897 first = false;
3898 } else {
3899 // Previous iterations consumed the root element of the heap.
3900 // Pop root element off of the heap (sift down).
3901 heap[0] = heap[heapSize];
3902 for (uint32_t parentIndex = 0;;) {
3903 uint32_t childIndex = parentIndex * 2 + 1;
3904 if (childIndex >= heapSize) {
3905 break;
3906 }
3907
3908 if (childIndex + 1 < heapSize &&
3909 heap[childIndex + 1].distance < heap[childIndex].distance) {
3910 childIndex += 1;
3911 }
3912
3913 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3914 break;
3915 }
3916
3917 swap(heap[parentIndex], heap[childIndex]);
3918 parentIndex = childIndex;
3919 }
3920
3921#if DEBUG_POINTER_ASSIGNMENT
3922 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003923 for (size_t j = 0; j < heapSize; j++) {
3924 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3925 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003926 }
3927#endif
3928 }
3929
3930 heapSize -= 1;
3931
3932 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3933 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3934
3935 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3936 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3937
3938 matchedCurrentBits.markBit(currentPointerIndex);
3939 matchedLastBits.markBit(lastPointerIndex);
3940
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003941 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3942 current.rawPointerData.pointers[currentPointerIndex].id = id;
3943 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3944 current.rawPointerData.markIdBit(id,
3945 current.rawPointerData.isHovering(
3946 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003947 usedIdBits.markBit(id);
3948
3949#if DEBUG_POINTER_ASSIGNMENT
3950 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3951 ", distance=%" PRIu64,
3952 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3953#endif
3954 break;
3955 }
3956 }
3957
3958 // Assign fresh ids to pointers that were not matched in the process.
3959 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3960 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3961 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3962
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003963 current.rawPointerData.pointers[currentPointerIndex].id = id;
3964 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3965 current.rawPointerData.markIdBit(id,
3966 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003967
3968#if DEBUG_POINTER_ASSIGNMENT
3969 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3970#endif
3971 }
3972}
3973
3974int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3975 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3976 return AKEY_STATE_VIRTUAL;
3977 }
3978
3979 for (const VirtualKey& virtualKey : mVirtualKeys) {
3980 if (virtualKey.keyCode == keyCode) {
3981 return AKEY_STATE_UP;
3982 }
3983 }
3984
3985 return AKEY_STATE_UNKNOWN;
3986}
3987
3988int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3989 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3990 return AKEY_STATE_VIRTUAL;
3991 }
3992
3993 for (const VirtualKey& virtualKey : mVirtualKeys) {
3994 if (virtualKey.scanCode == scanCode) {
3995 return AKEY_STATE_UP;
3996 }
3997 }
3998
3999 return AKEY_STATE_UNKNOWN;
4000}
4001
4002bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4003 const int32_t* keyCodes, uint8_t* outFlags) {
4004 for (const VirtualKey& virtualKey : mVirtualKeys) {
4005 for (size_t i = 0; i < numCodes; i++) {
4006 if (virtualKey.keyCode == keyCodes[i]) {
4007 outFlags[i] = 1;
4008 }
4009 }
4010 }
4011
4012 return true;
4013}
4014
4015std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4016 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004017 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004018 return std::make_optional(mPointerController->getDisplayId());
4019 } else {
4020 return std::make_optional(mViewport.displayId);
4021 }
4022 }
4023 return std::nullopt;
4024}
4025
Prabir Pradhand7482e72021-03-09 13:54:55 -08004026void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
4027 if (isPerWindowInputRotationEnabled()) {
4028 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4029 // space that is oriented with the viewport.
4030 rotateDelta(mViewport.orientation, &dx, &dy);
4031 }
4032
4033 mPointerController->move(dx, dy);
4034}
4035
4036std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4037 float x = 0;
4038 float y = 0;
4039 mPointerController->getPosition(&x, &y);
4040
4041 if (!isPerWindowInputRotationEnabled()) return {x, y};
4042 if (!mViewport.isValid()) return {x, y};
4043
4044 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4045 // to InputReader's un-rotated coordinate space.
4046 const int32_t orientation = getInverseRotation(mViewport.orientation);
4047 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4048 return {x, y};
4049}
4050
4051void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4052 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4053 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4054 // coordinate space that is oriented with the viewport.
4055 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4056 }
4057
4058 mPointerController->setPosition(x, y);
4059}
4060
4061void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4062 BitSet32 spotIdBits, int32_t displayId) {
4063 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4064
4065 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4066 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4067 float x = spotCoords[index].getX();
4068 float y = spotCoords[index].getY();
4069 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4070
4071 if (isPerWindowInputRotationEnabled()) {
4072 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4073 // coordinate space.
4074 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4075 }
4076
4077 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4078 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4079 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4080 }
4081
4082 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4083}
4084
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004085} // namespace android