blob: 57f522539bab9477fd87ff0019d7fb3de2c0004a [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
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
24
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070025#include "CursorButtonAccumulator.h"
26#include "CursorScrollAccumulator.h"
27#include "TouchButtonAccumulator.h"
28#include "TouchCursorInputMapperCommon.h"
29
30namespace android {
31
32// --- Constants ---
33
34// Maximum amount of latency to add to touch events while waiting for data from an
35// external stylus.
36static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
37
38// Maximum amount of time to wait on touch data before pushing out new pressure data.
39static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
40
41// Artificial latency on synthetic events created from stylus data without corresponding touch
42// data.
43static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
44
45// --- Static Definitions ---
46
47template <typename T>
48inline static void swap(T& a, T& b) {
49 T temp = a;
50 a = b;
51 b = temp;
52}
53
54static float calculateCommonVector(float a, float b) {
55 if (a > 0 && b > 0) {
56 return a < b ? a : b;
57 } else if (a < 0 && b < 0) {
58 return a > b ? a : b;
59 } else {
60 return 0;
61 }
62}
63
64inline static float distance(float x1, float y1, float x2, float y2) {
65 return hypotf(x1 - x2, y1 - y2);
66}
67
68inline static int32_t signExtendNybble(int32_t value) {
69 return value >= 8 ? value - 16 : value;
70}
71
72// --- RawPointerAxes ---
73
74RawPointerAxes::RawPointerAxes() {
75 clear();
76}
77
78void RawPointerAxes::clear() {
79 x.clear();
80 y.clear();
81 pressure.clear();
82 touchMajor.clear();
83 touchMinor.clear();
84 toolMajor.clear();
85 toolMinor.clear();
86 orientation.clear();
87 distance.clear();
88 tiltX.clear();
89 tiltY.clear();
90 trackingId.clear();
91 slot.clear();
92}
93
94// --- RawPointerData ---
95
96RawPointerData::RawPointerData() {
97 clear();
98}
99
100void RawPointerData::clear() {
101 pointerCount = 0;
102 clearIdBits();
103}
104
105void RawPointerData::copyFrom(const RawPointerData& other) {
106 pointerCount = other.pointerCount;
107 hoveringIdBits = other.hoveringIdBits;
108 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800109 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700110
111 for (uint32_t i = 0; i < pointerCount; i++) {
112 pointers[i] = other.pointers[i];
113
114 int id = pointers[i].id;
115 idToIndex[id] = other.idToIndex[id];
116 }
117}
118
119void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
120 float x = 0, y = 0;
121 uint32_t count = touchingIdBits.count();
122 if (count) {
123 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
124 uint32_t id = idBits.clearFirstMarkedBit();
125 const Pointer& pointer = pointerForId(id);
126 x += pointer.x;
127 y += pointer.y;
128 }
129 x /= count;
130 y /= count;
131 }
132 *outX = x;
133 *outY = y;
134}
135
136// --- CookedPointerData ---
137
138CookedPointerData::CookedPointerData() {
139 clear();
140}
141
142void CookedPointerData::clear() {
143 pointerCount = 0;
144 hoveringIdBits.clear();
145 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800146 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000147 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700148}
149
150void CookedPointerData::copyFrom(const CookedPointerData& other) {
151 pointerCount = other.pointerCount;
152 hoveringIdBits = other.hoveringIdBits;
153 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000154 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700155
156 for (uint32_t i = 0; i < pointerCount; i++) {
157 pointerProperties[i].copyFrom(other.pointerProperties[i]);
158 pointerCoords[i].copyFrom(other.pointerCoords[i]);
159
160 int id = pointerProperties[i].id;
161 idToIndex[id] = other.idToIndex[id];
162 }
163}
164
165// --- TouchInputMapper ---
166
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800167TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
168 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700169 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100170 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800171 mRawSurfaceWidth(-1),
172 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700173 mSurfaceLeft(0),
174 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700175 mSurfaceRight(0),
176 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700177 mPhysicalWidth(-1),
178 mPhysicalHeight(-1),
179 mPhysicalLeft(0),
180 mPhysicalTop(0),
181 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
182
183TouchInputMapper::~TouchInputMapper() {}
184
185uint32_t TouchInputMapper::getSources() {
186 return mSource;
187}
188
189void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
190 InputMapper::populateDeviceInfo(info);
191
Michael Wright227c5542020-07-02 18:30:52 +0100192 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700193 info->addMotionRange(mOrientedRanges.x);
194 info->addMotionRange(mOrientedRanges.y);
195 info->addMotionRange(mOrientedRanges.pressure);
196
Chris Yef74dc422020-09-02 22:41:50 -0700197 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700198 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
199 //
200 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
201 // motion, i.e. the hardware dimensions, as the finger could move completely across the
202 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700203 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
204 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
205 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
206 x.fuzz, x.resolution);
207 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
208 y.fuzz, y.resolution);
209 }
210
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700211 if (mOrientedRanges.haveSize) {
212 info->addMotionRange(mOrientedRanges.size);
213 }
214
215 if (mOrientedRanges.haveTouchSize) {
216 info->addMotionRange(mOrientedRanges.touchMajor);
217 info->addMotionRange(mOrientedRanges.touchMinor);
218 }
219
220 if (mOrientedRanges.haveToolSize) {
221 info->addMotionRange(mOrientedRanges.toolMajor);
222 info->addMotionRange(mOrientedRanges.toolMinor);
223 }
224
225 if (mOrientedRanges.haveOrientation) {
226 info->addMotionRange(mOrientedRanges.orientation);
227 }
228
229 if (mOrientedRanges.haveDistance) {
230 info->addMotionRange(mOrientedRanges.distance);
231 }
232
233 if (mOrientedRanges.haveTilt) {
234 info->addMotionRange(mOrientedRanges.tilt);
235 }
236
237 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
238 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
239 0.0f);
240 }
241 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
242 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
243 0.0f);
244 }
Michael Wright227c5542020-07-02 18:30:52 +0100245 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700246 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
247 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
248 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
249 x.fuzz, x.resolution);
250 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
251 y.fuzz, y.resolution);
252 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
253 x.fuzz, x.resolution);
254 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
255 y.fuzz, y.resolution);
256 }
257 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
258 }
259}
260
261void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700262 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800263 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700264 dumpParameters(dump);
265 dumpVirtualKeys(dump);
266 dumpRawPointerAxes(dump);
267 dumpCalibration(dump);
268 dumpAffineTransformation(dump);
269 dumpSurface(dump);
270
271 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
272 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
273 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
274 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
275 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
276 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
277 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
278 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
279 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
280 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
281 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
282 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
283 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
284 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
285 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
286 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
287 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
288
289 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
290 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
291 mLastRawState.rawPointerData.pointerCount);
292 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
293 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
294 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
295 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
296 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
297 "toolType=%d, isHovering=%s\n",
298 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
299 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
300 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
301 pointer.distance, pointer.toolType, toString(pointer.isHovering));
302 }
303
304 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
305 mLastCookedState.buttonState);
306 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
307 mLastCookedState.cookedPointerData.pointerCount);
308 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
309 const PointerProperties& pointerProperties =
310 mLastCookedState.cookedPointerData.pointerProperties[i];
311 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000312 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
313 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
314 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700315 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
316 "toolType=%d, isHovering=%s\n",
317 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
327 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
328 pointerProperties.toolType,
329 toString(mLastCookedState.cookedPointerData.isHovering(i)));
330 }
331
332 dump += INDENT3 "Stylus Fusion:\n";
333 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
334 toString(mExternalStylusConnected));
335 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
336 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
337 mExternalStylusFusionTimeout);
338 dump += INDENT3 "External Stylus State:\n";
339 dumpStylusState(dump, mExternalStylusState);
340
Michael Wright227c5542020-07-02 18:30:52 +0100341 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700342 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
343 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
344 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
345 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
346 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
347 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
348 }
349}
350
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
352 uint32_t changes) {
353 InputMapper::configure(when, config, changes);
354
355 mConfig = *config;
356
357 if (!changes) { // first time only
358 // Configure basic parameters.
359 configureParameters();
360
361 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800362 mCursorScrollAccumulator.configure(getDeviceContext());
363 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364
365 // Configure absolute axis information.
366 configureRawPointerAxes();
367
368 // Prepare input device calibration.
369 parseCalibration();
370 resolveCalibration();
371 }
372
373 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
374 // Update location calibration to reflect current settings
375 updateAffineTransformation();
376 }
377
378 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
379 // Update pointer speed.
380 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
381 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
383 }
384
385 bool resetNeeded = false;
386 if (!changes ||
387 (changes &
388 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800389 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
391 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
392 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
393 // Configure device sources, surface dimensions, orientation and
394 // scaling factors.
395 configureSurface(when, &resetNeeded);
396 }
397
398 if (changes && resetNeeded) {
399 // Send reset, unless this is the first time the device has been configured,
400 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +0000401 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700402 getListener().notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700403 }
404}
405
406void TouchInputMapper::resolveExternalStylusPresence() {
407 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800408 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700409 mExternalStylusConnected = !devices.empty();
410
411 if (!mExternalStylusConnected) {
412 resetExternalStylus();
413 }
414}
415
416void TouchInputMapper::configureParameters() {
417 // Use the pointer presentation mode for devices that do not support distinct
418 // multitouch. The spot-based presentation relies on being able to accurately
419 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800420 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100421 ? Parameters::GestureMode::SINGLE_TOUCH
422 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423
424 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800425 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
426 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700427 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100428 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700429 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100430 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700431 } else if (gestureModeString != "default") {
432 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
433 }
434 }
435
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800436 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700437 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100438 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800439 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700440 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100441 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800442 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
443 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444 // The device is a cursor device with a touch pad attached.
445 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100446 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447 } else {
448 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100449 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450 }
451
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800452 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700453
454 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800455 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
456 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100458 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100460 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700461 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100462 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100464 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700465 } else if (deviceTypeString != "default") {
466 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
467 }
468 }
469
Michael Wright227c5542020-07-02 18:30:52 +0100470 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800471 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
472 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700473
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700474 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
475 String8 orientationString;
476 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientation"),
477 orientationString)) {
478 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
479 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
480 } else if (orientationString == "ORIENTATION_90") {
481 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
482 } else if (orientationString == "ORIENTATION_180") {
483 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
484 } else if (orientationString == "ORIENTATION_270") {
485 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
486 } else if (orientationString != "ORIENTATION_0") {
487 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.string());
488 }
489 }
490
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700491 mParameters.hasAssociatedDisplay = false;
492 mParameters.associatedDisplayIsExternal = false;
493 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100494 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
495 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100497 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800498 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700499 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800500 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
501 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
503 }
504 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800505 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700506 mParameters.hasAssociatedDisplay = true;
507 }
508
509 // Initial downs on external touch devices should wake the device.
510 // Normally we don't do this for internal touch screens to prevent them from waking
511 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800512 mParameters.wake = getDeviceContext().isExternal();
513 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514}
515
516void TouchInputMapper::dumpParameters(std::string& dump) {
517 dump += INDENT3 "Parameters:\n";
518
Dominik Laskowski75788452021-02-09 18:51:25 -0800519 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700520
Dominik Laskowski75788452021-02-09 18:51:25 -0800521 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700522
523 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
524 "displayId='%s'\n",
525 toString(mParameters.hasAssociatedDisplay),
526 toString(mParameters.associatedDisplayIsExternal),
527 mParameters.uniqueDisplayId.c_str());
528 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800529 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700530}
531
532void TouchInputMapper::configureRawPointerAxes() {
533 mRawPointerAxes.clear();
534}
535
536void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
537 dump += INDENT3 "Raw Touch Axes:\n";
538 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
549 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
550 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
551}
552
553bool TouchInputMapper::hasExternalStylus() const {
554 return mExternalStylusConnected;
555}
556
557/**
558 * Determine which DisplayViewport to use.
559 * 1. If display port is specified, return the matching viewport. If matching viewport not
560 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800561 * 2. Always use the suggested viewport from WindowManagerService for pointers.
562 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700563 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800564 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700565 */
566std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800567 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800568 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700569 if (displayPort) {
570 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800571 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700572 }
573
Michael Wright227c5542020-07-02 18:30:52 +0100574 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800575 std::optional<DisplayViewport> viewport =
576 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
577 if (viewport) {
578 return viewport;
579 } else {
580 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
581 mConfig.defaultPointerDisplayId);
582 }
583 }
584
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700585 // Check if uniqueDisplayId is specified in idc file.
586 if (!mParameters.uniqueDisplayId.empty()) {
587 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
588 }
589
590 ViewportType viewportTypeToUse;
591 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100592 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700593 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100594 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700595 }
596
597 std::optional<DisplayViewport> viewport =
598 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100599 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700600 ALOGW("Input device %s should be associated with external display, "
601 "fallback to internal one for the external viewport is not found.",
602 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100603 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700604 }
605
606 return viewport;
607 }
608
609 // No associated display, return a non-display viewport.
610 DisplayViewport newViewport;
611 // Raw width and height in the natural orientation.
612 int32_t rawWidth = mRawPointerAxes.getRawWidth();
613 int32_t rawHeight = mRawPointerAxes.getRawHeight();
614 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
615 return std::make_optional(newViewport);
616}
617
618void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100619 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700620
621 resolveExternalStylusPresence();
622
623 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100624 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000625 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700626 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100627 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700628 if (hasStylus()) {
629 mSource |= AINPUT_SOURCE_STYLUS;
630 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800631 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700632 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100633 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700634 if (hasStylus()) {
635 mSource |= AINPUT_SOURCE_STYLUS;
636 }
637 if (hasExternalStylus()) {
638 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
639 }
Michael Wright227c5542020-07-02 18:30:52 +0100640 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700641 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100642 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700643 } else {
644 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100645 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700646 }
647
648 // Ensure we have valid X and Y axes.
649 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
650 ALOGW("Touch device '%s' did not report support for X or Y axis! "
651 "The device will be inoperable.",
652 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100653 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700654 return;
655 }
656
657 // Get associated display dimensions.
658 std::optional<DisplayViewport> newViewport = findViewport();
659 if (!newViewport) {
660 ALOGI("Touch device '%s' could not query the properties of its associated "
661 "display. The device will be inoperable until the display size "
662 "becomes available.",
663 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100664 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700665 return;
666 }
667
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000668 if (!newViewport->isActive) {
669 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
670 getDeviceName().c_str(), getDeviceId());
671 mDeviceMode = DeviceMode::DISABLED;
672 return;
673 }
674
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700675 // Raw width and height in the natural orientation.
676 int32_t rawWidth = mRawPointerAxes.getRawWidth();
677 int32_t rawHeight = mRawPointerAxes.getRawHeight();
678
679 bool viewportChanged = mViewport != *newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700680 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700681 if (viewportChanged) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700682 bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700683 mViewport = *newViewport;
684
Michael Wright227c5542020-07-02 18:30:52 +0100685 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700686 // Convert rotated viewport to natural surface coordinates.
687 int32_t naturalLogicalWidth, naturalLogicalHeight;
688 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
689 int32_t naturalPhysicalLeft, naturalPhysicalTop;
690 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700691
692 // Apply the inverse of the input device orientation so that the surface is configured
693 // in the same orientation as the device. The input device orientation will be
694 // re-applied to mSurfaceOrientation.
695 const int32_t naturalSurfaceOrientation =
696 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
697 switch (naturalSurfaceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700698 case DISPLAY_ORIENTATION_90:
699 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
700 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
701 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
702 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800703 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700704 naturalPhysicalTop = mViewport.physicalLeft;
705 naturalDeviceWidth = mViewport.deviceHeight;
706 naturalDeviceHeight = mViewport.deviceWidth;
707 break;
708 case DISPLAY_ORIENTATION_180:
709 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
710 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
711 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
712 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
713 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
714 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
715 naturalDeviceWidth = mViewport.deviceWidth;
716 naturalDeviceHeight = mViewport.deviceHeight;
717 break;
718 case DISPLAY_ORIENTATION_270:
719 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
720 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
721 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
722 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
723 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800724 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700725 naturalDeviceWidth = mViewport.deviceHeight;
726 naturalDeviceHeight = mViewport.deviceWidth;
727 break;
728 case DISPLAY_ORIENTATION_0:
729 default:
730 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
731 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
732 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
733 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
734 naturalPhysicalLeft = mViewport.physicalLeft;
735 naturalPhysicalTop = mViewport.physicalTop;
736 naturalDeviceWidth = mViewport.deviceWidth;
737 naturalDeviceHeight = mViewport.deviceHeight;
738 break;
739 }
740
741 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
742 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
743 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
744 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
745 }
746
747 mPhysicalWidth = naturalPhysicalWidth;
748 mPhysicalHeight = naturalPhysicalHeight;
749 mPhysicalLeft = naturalPhysicalLeft;
750 mPhysicalTop = naturalPhysicalTop;
751
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000752 // TODO(prabirmsp): Cleanup surface bounds.
753 // When per-window input rotation is enabled, InputReader works in the display
754 // space, so the surface bounds are the bounds of the display device.
755 const int32_t oldSurfaceWidth = mRawSurfaceWidth;
756 const int32_t oldSurfaceHeight = mRawSurfaceHeight;
757 mRawSurfaceWidth = naturalDeviceWidth;
758 mRawSurfaceHeight = naturalDeviceHeight;
759 mSurfaceLeft = 0;
760 mSurfaceTop = 0;
761 mSurfaceRight = mRawSurfaceWidth;
762 mSurfaceBottom = mRawSurfaceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700763
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000764 // InputReader works in the un-rotated display coordinate space, so we don't need to do
765 // anything if the device is already orientation-aware. If the device is not
766 // orientation-aware, then we need to apply the inverse rotation of the display so that
767 // when the display rotation is applied later as a part of the per-window transform, we
768 // get the expected screen coordinates.
769 mSurfaceOrientation = mParameters.orientationAware
770 ? DISPLAY_ORIENTATION_0
771 : getInverseRotation(mViewport.orientation);
772 // For orientation-aware devices that work in the un-rotated coordinate space, the
773 // viewport update should be skipped if it is only a change in the orientation.
774 skipViewportUpdate = mParameters.orientationAware &&
775 mRawSurfaceWidth == oldSurfaceWidth && mRawSurfaceHeight == oldSurfaceHeight &&
776 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700777
778 // Apply the input device orientation for the device.
779 mSurfaceOrientation =
780 (mSurfaceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700781 } else {
782 mPhysicalWidth = rawWidth;
783 mPhysicalHeight = rawHeight;
784 mPhysicalLeft = 0;
785 mPhysicalTop = 0;
786
Arthur Hung4197f6b2020-03-16 15:39:59 +0800787 mRawSurfaceWidth = rawWidth;
788 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700789 mSurfaceLeft = 0;
790 mSurfaceTop = 0;
791 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
792 }
793 }
794
795 // If moving between pointer modes, need to reset some state.
796 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
797 if (deviceModeChanged) {
798 mOrientedRanges.clear();
799 }
800
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800801 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
802 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100803 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800804 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000805 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
806 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800807 if (mPointerController == nullptr) {
808 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700809 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000810 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800811 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
812 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700813 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100814 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700815 }
816
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700817 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700818 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
819 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800820 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700821 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
822
823 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800824 mXScale = float(mRawSurfaceWidth) / rawWidth;
825 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700826 mXTranslate = -mSurfaceLeft;
827 mYTranslate = -mSurfaceTop;
828 mXPrecision = 1.0f / mXScale;
829 mYPrecision = 1.0f / mYScale;
830
831 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
832 mOrientedRanges.x.source = mSource;
833 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
834 mOrientedRanges.y.source = mSource;
835
836 configureVirtualKeys();
837
838 // Scale factor for terms that are not oriented in a particular axis.
839 // If the pixels are square then xScale == yScale otherwise we fake it
840 // by choosing an average.
841 mGeometricScale = avg(mXScale, mYScale);
842
843 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800844 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700845
846 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100847 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700848 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
849 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
850 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
851 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
852 } else {
853 mSizeScale = 0.0f;
854 }
855
856 mOrientedRanges.haveTouchSize = true;
857 mOrientedRanges.haveToolSize = true;
858 mOrientedRanges.haveSize = true;
859
860 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
861 mOrientedRanges.touchMajor.source = mSource;
862 mOrientedRanges.touchMajor.min = 0;
863 mOrientedRanges.touchMajor.max = diagonalSize;
864 mOrientedRanges.touchMajor.flat = 0;
865 mOrientedRanges.touchMajor.fuzz = 0;
866 mOrientedRanges.touchMajor.resolution = 0;
867
868 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
869 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
870
871 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
872 mOrientedRanges.toolMajor.source = mSource;
873 mOrientedRanges.toolMajor.min = 0;
874 mOrientedRanges.toolMajor.max = diagonalSize;
875 mOrientedRanges.toolMajor.flat = 0;
876 mOrientedRanges.toolMajor.fuzz = 0;
877 mOrientedRanges.toolMajor.resolution = 0;
878
879 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
880 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
881
882 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
883 mOrientedRanges.size.source = mSource;
884 mOrientedRanges.size.min = 0;
885 mOrientedRanges.size.max = 1.0;
886 mOrientedRanges.size.flat = 0;
887 mOrientedRanges.size.fuzz = 0;
888 mOrientedRanges.size.resolution = 0;
889 } else {
890 mSizeScale = 0.0f;
891 }
892
893 // Pressure factors.
894 mPressureScale = 0;
895 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100896 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
897 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700898 if (mCalibration.havePressureScale) {
899 mPressureScale = mCalibration.pressureScale;
900 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
901 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
902 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
903 }
904 }
905
906 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
907 mOrientedRanges.pressure.source = mSource;
908 mOrientedRanges.pressure.min = 0;
909 mOrientedRanges.pressure.max = pressureMax;
910 mOrientedRanges.pressure.flat = 0;
911 mOrientedRanges.pressure.fuzz = 0;
912 mOrientedRanges.pressure.resolution = 0;
913
914 // Tilt
915 mTiltXCenter = 0;
916 mTiltXScale = 0;
917 mTiltYCenter = 0;
918 mTiltYScale = 0;
919 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
920 if (mHaveTilt) {
921 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
922 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
923 mTiltXScale = M_PI / 180;
924 mTiltYScale = M_PI / 180;
925
Tatsunosuke Tobita35e05532021-06-30 14:49:32 +0900926 if (mRawPointerAxes.tiltX.resolution) {
927 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
928 }
929 if (mRawPointerAxes.tiltY.resolution) {
930 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
931 }
932
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700933 mOrientedRanges.haveTilt = true;
934
935 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
936 mOrientedRanges.tilt.source = mSource;
937 mOrientedRanges.tilt.min = 0;
938 mOrientedRanges.tilt.max = M_PI_2;
939 mOrientedRanges.tilt.flat = 0;
940 mOrientedRanges.tilt.fuzz = 0;
941 mOrientedRanges.tilt.resolution = 0;
942 }
943
944 // Orientation
945 mOrientationScale = 0;
946 if (mHaveTilt) {
947 mOrientedRanges.haveOrientation = true;
948
949 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
950 mOrientedRanges.orientation.source = mSource;
951 mOrientedRanges.orientation.min = -M_PI;
952 mOrientedRanges.orientation.max = M_PI;
953 mOrientedRanges.orientation.flat = 0;
954 mOrientedRanges.orientation.fuzz = 0;
955 mOrientedRanges.orientation.resolution = 0;
956 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100957 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700958 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100959 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700960 if (mRawPointerAxes.orientation.valid) {
961 if (mRawPointerAxes.orientation.maxValue > 0) {
962 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
963 } else if (mRawPointerAxes.orientation.minValue < 0) {
964 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
965 } else {
966 mOrientationScale = 0;
967 }
968 }
969 }
970
971 mOrientedRanges.haveOrientation = true;
972
973 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
974 mOrientedRanges.orientation.source = mSource;
975 mOrientedRanges.orientation.min = -M_PI_2;
976 mOrientedRanges.orientation.max = M_PI_2;
977 mOrientedRanges.orientation.flat = 0;
978 mOrientedRanges.orientation.fuzz = 0;
979 mOrientedRanges.orientation.resolution = 0;
980 }
981
982 // Distance
983 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100984 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
985 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700986 if (mCalibration.haveDistanceScale) {
987 mDistanceScale = mCalibration.distanceScale;
988 } else {
989 mDistanceScale = 1.0f;
990 }
991 }
992
993 mOrientedRanges.haveDistance = true;
994
995 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
996 mOrientedRanges.distance.source = mSource;
997 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
998 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
999 mOrientedRanges.distance.flat = 0;
1000 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
1001 mOrientedRanges.distance.resolution = 0;
1002 }
1003
1004 // Compute oriented precision, scales and ranges.
1005 // Note that the maximum value reported is an inclusive maximum value so it is one
1006 // unit less than the total width or height of surface.
1007 switch (mSurfaceOrientation) {
1008 case DISPLAY_ORIENTATION_90:
1009 case DISPLAY_ORIENTATION_270:
1010 mOrientedXPrecision = mYPrecision;
1011 mOrientedYPrecision = mXPrecision;
1012
1013 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001014 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001015 mOrientedRanges.x.flat = 0;
1016 mOrientedRanges.x.fuzz = 0;
1017 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
1018
1019 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001020 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001021 mOrientedRanges.y.flat = 0;
1022 mOrientedRanges.y.fuzz = 0;
1023 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
1024 break;
1025
1026 default:
1027 mOrientedXPrecision = mXPrecision;
1028 mOrientedYPrecision = mYPrecision;
1029
1030 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001031 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032 mOrientedRanges.x.flat = 0;
1033 mOrientedRanges.x.fuzz = 0;
1034 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1035
1036 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001037 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001038 mOrientedRanges.y.flat = 0;
1039 mOrientedRanges.y.fuzz = 0;
1040 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1041 break;
1042 }
1043
1044 // Location
1045 updateAffineTransformation();
1046
Michael Wright227c5542020-07-02 18:30:52 +01001047 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001048 // Compute pointer gesture detection parameters.
1049 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001050 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001051
1052 // Scale movements such that one whole swipe of the touch pad covers a
1053 // given area relative to the diagonal size of the display when no acceleration
1054 // is applied.
1055 // Assume that the touch pad has a square aspect ratio such that movements in
1056 // X and Y of the same number of raw units cover the same physical distance.
1057 mPointerXMovementScale =
1058 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1059 mPointerYMovementScale = mPointerXMovementScale;
1060
1061 // Scale zooms to cover a smaller range of the display than movements do.
1062 // This value determines the area around the pointer that is affected by freeform
1063 // pointer gestures.
1064 mPointerXZoomScale =
1065 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1066 mPointerYZoomScale = mPointerXZoomScale;
1067
1068 // Max width between pointers to detect a swipe gesture is more than some fraction
1069 // of the diagonal axis of the touch pad. Touches that are wider than this are
1070 // translated into freeform gestures.
1071 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1072
1073 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001074 const nsecs_t readTime = when; // synthetic event
1075 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001076 }
1077
1078 // Inform the dispatcher about the changes.
1079 *outResetNeeded = true;
1080 bumpGeneration();
1081 }
1082}
1083
1084void TouchInputMapper::dumpSurface(std::string& dump) {
1085 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001086 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1087 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001088 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1089 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001090 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1091 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1093 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1094 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1095 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1096 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1097}
1098
1099void TouchInputMapper::configureVirtualKeys() {
1100 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001101 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001102
1103 mVirtualKeys.clear();
1104
1105 if (virtualKeyDefinitions.size() == 0) {
1106 return;
1107 }
1108
1109 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1110 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1111 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1112 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1113
1114 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1115 VirtualKey virtualKey;
1116
1117 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1118 int32_t keyCode;
1119 int32_t dummyKeyMetaState;
1120 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001121 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1122 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1124 continue; // drop the key
1125 }
1126
1127 virtualKey.keyCode = keyCode;
1128 virtualKey.flags = flags;
1129
1130 // convert the key definition's display coordinates into touch coordinates for a hit box
1131 int32_t halfWidth = virtualKeyDefinition.width / 2;
1132 int32_t halfHeight = virtualKeyDefinition.height / 2;
1133
1134 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001135 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 touchScreenLeft;
1137 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001138 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001140 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1141 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001143 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1144 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 touchScreenTop;
1146 mVirtualKeys.push_back(virtualKey);
1147 }
1148}
1149
1150void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1151 if (!mVirtualKeys.empty()) {
1152 dump += INDENT3 "Virtual Keys:\n";
1153
1154 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1155 const VirtualKey& virtualKey = mVirtualKeys[i];
1156 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1157 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1158 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1159 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1160 }
1161 }
1162}
1163
1164void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001165 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 Calibration& out = mCalibration;
1167
1168 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 String8 sizeCalibrationString;
1171 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1172 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 } else if (sizeCalibrationString != "default") {
1183 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1184 }
1185 }
1186
1187 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1188 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1189 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1190
1191 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 String8 pressureCalibrationString;
1194 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1195 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001198 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (pressureCalibrationString != "default") {
1202 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1203 pressureCalibrationString.string());
1204 }
1205 }
1206
1207 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1208
1209 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 String8 orientationCalibrationString;
1212 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1213 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001214 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 } else if (orientationCalibrationString != "default") {
1220 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1221 orientationCalibrationString.string());
1222 }
1223 }
1224
1225 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001226 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 String8 distanceCalibrationString;
1228 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1229 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001230 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001232 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 } else if (distanceCalibrationString != "default") {
1234 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1235 distanceCalibrationString.string());
1236 }
1237 }
1238
1239 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1240
Michael Wright227c5542020-07-02 18:30:52 +01001241 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 String8 coverageCalibrationString;
1243 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1244 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001245 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001247 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 } else if (coverageCalibrationString != "default") {
1249 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1250 coverageCalibrationString.string());
1251 }
1252 }
1253}
1254
1255void TouchInputMapper::resolveCalibration() {
1256 // Size
1257 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001258 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1259 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 }
1261 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001262 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 }
1264
1265 // Pressure
1266 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001267 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1268 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001271 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 }
1273
1274 // Orientation
1275 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001276 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1277 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 }
1279 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001280 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 }
1282
1283 // Distance
1284 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001285 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1286 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 }
1288 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001289 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 }
1291
1292 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001293 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1294 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 }
1296}
1297
1298void TouchInputMapper::dumpCalibration(std::string& dump) {
1299 dump += INDENT3 "Calibration:\n";
1300
1301 // Size
1302 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001303 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += INDENT4 "touch.size.calibration: none\n";
1305 break;
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.size.calibration: geometric\n";
1308 break;
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.size.calibration: diameter\n";
1311 break;
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.size.calibration: box\n";
1314 break;
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.size.calibration: area\n";
1317 break;
1318 default:
1319 ALOG_ASSERT(false);
1320 }
1321
1322 if (mCalibration.haveSizeScale) {
1323 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1324 }
1325
1326 if (mCalibration.haveSizeBias) {
1327 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1328 }
1329
1330 if (mCalibration.haveSizeIsSummed) {
1331 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1332 toString(mCalibration.sizeIsSummed));
1333 }
1334
1335 // Pressure
1336 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001337 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 dump += INDENT4 "touch.pressure.calibration: none\n";
1339 break;
Michael Wright227c5542020-07-02 18:30:52 +01001340 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.pressure.calibration: physical\n";
1342 break;
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1345 break;
1346 default:
1347 ALOG_ASSERT(false);
1348 }
1349
1350 if (mCalibration.havePressureScale) {
1351 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1352 }
1353
1354 // Orientation
1355 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001356 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 dump += INDENT4 "touch.orientation.calibration: none\n";
1358 break;
Michael Wright227c5542020-07-02 18:30:52 +01001359 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1361 break;
Michael Wright227c5542020-07-02 18:30:52 +01001362 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001363 dump += INDENT4 "touch.orientation.calibration: vector\n";
1364 break;
1365 default:
1366 ALOG_ASSERT(false);
1367 }
1368
1369 // Distance
1370 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001371 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001372 dump += INDENT4 "touch.distance.calibration: none\n";
1373 break;
Michael Wright227c5542020-07-02 18:30:52 +01001374 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001375 dump += INDENT4 "touch.distance.calibration: scaled\n";
1376 break;
1377 default:
1378 ALOG_ASSERT(false);
1379 }
1380
1381 if (mCalibration.haveDistanceScale) {
1382 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1383 }
1384
1385 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001386 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001387 dump += INDENT4 "touch.coverage.calibration: none\n";
1388 break;
Michael Wright227c5542020-07-02 18:30:52 +01001389 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001390 dump += INDENT4 "touch.coverage.calibration: box\n";
1391 break;
1392 default:
1393 ALOG_ASSERT(false);
1394 }
1395}
1396
1397void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1398 dump += INDENT3 "Affine Transformation:\n";
1399
1400 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1401 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1402 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1403 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1404 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1405 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1406}
1407
1408void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001409 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410 mSurfaceOrientation);
1411}
1412
1413void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001414 mCursorButtonAccumulator.reset(getDeviceContext());
1415 mCursorScrollAccumulator.reset(getDeviceContext());
1416 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001417
1418 mPointerVelocityControl.reset();
1419 mWheelXVelocityControl.reset();
1420 mWheelYVelocityControl.reset();
1421
1422 mRawStatesPending.clear();
1423 mCurrentRawState.clear();
1424 mCurrentCookedState.clear();
1425 mLastRawState.clear();
1426 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001427 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001428 mSentHoverEnter = false;
1429 mHavePointerIds = false;
1430 mCurrentMotionAborted = false;
1431 mDownTime = 0;
1432
1433 mCurrentVirtualKey.down = false;
1434
1435 mPointerGesture.reset();
1436 mPointerSimple.reset();
1437 resetExternalStylus();
1438
1439 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001440 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001441 mPointerController->clearSpots();
1442 }
1443
1444 InputMapper::reset(when);
1445}
1446
1447void TouchInputMapper::resetExternalStylus() {
1448 mExternalStylusState.clear();
1449 mExternalStylusId = -1;
1450 mExternalStylusFusionTimeout = LLONG_MAX;
1451 mExternalStylusDataPending = false;
1452}
1453
1454void TouchInputMapper::clearStylusDataPendingFlags() {
1455 mExternalStylusDataPending = false;
1456 mExternalStylusFusionTimeout = LLONG_MAX;
1457}
1458
1459void TouchInputMapper::process(const RawEvent* rawEvent) {
1460 mCursorButtonAccumulator.process(rawEvent);
1461 mCursorScrollAccumulator.process(rawEvent);
1462 mTouchButtonAccumulator.process(rawEvent);
1463
1464 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001465 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001466 }
1467}
1468
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001469void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001470 // Push a new state.
1471 mRawStatesPending.emplace_back();
1472
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001473 RawState& next = mRawStatesPending.back();
1474 next.clear();
1475 next.when = when;
1476 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001477
1478 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001479 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001480 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1481
1482 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001483 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1484 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485 mCursorScrollAccumulator.finishSync();
1486
1487 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001488 syncTouch(when, &next);
1489
1490 // The last RawState is the actually second to last, since we just added a new state
1491 const RawState& last =
1492 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001493
1494 // Assign pointer ids.
1495 if (!mHavePointerIds) {
1496 assignPointerIds(last, next);
1497 }
1498
1499#if DEBUG_RAW_EVENTS
1500 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001501 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001502 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1503 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1504 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1505 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001506#endif
1507
Arthur Hung9ad18942021-06-19 02:04:46 +00001508 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1509 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1510 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1511 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1512 next.rawPointerData.hoveringIdBits.value);
1513 }
1514
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001515 processRawTouches(false /*timeout*/);
1516}
1517
1518void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001519 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001520 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001521 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001522 mCurrentCookedState.clear();
1523 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 return;
1525 }
1526
1527 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1528 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1529 // touching the current state will only observe the events that have been dispatched to the
1530 // rest of the pipeline.
1531 const size_t N = mRawStatesPending.size();
1532 size_t count;
1533 for (count = 0; count < N; count++) {
1534 const RawState& next = mRawStatesPending[count];
1535
1536 // A failure to assign the stylus id means that we're waiting on stylus data
1537 // and so should defer the rest of the pipeline.
1538 if (assignExternalStylusId(next, timeout)) {
1539 break;
1540 }
1541
1542 // All ready to go.
1543 clearStylusDataPendingFlags();
1544 mCurrentRawState.copyFrom(next);
1545 if (mCurrentRawState.when < mLastRawState.when) {
1546 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001547 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001548 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001549 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550 }
1551 if (count != 0) {
1552 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1553 }
1554
1555 if (mExternalStylusDataPending) {
1556 if (timeout) {
1557 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1558 clearStylusDataPendingFlags();
1559 mCurrentRawState.copyFrom(mLastRawState);
1560#if DEBUG_STYLUS_FUSION
1561 ALOGD("Timeout expired, synthesizing event with new stylus data");
1562#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001563 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1564 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001565 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1566 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1567 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1568 }
1569 }
1570}
1571
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001572void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001573 // Always start with a clean state.
1574 mCurrentCookedState.clear();
1575
1576 // Apply stylus buttons to current raw state.
1577 applyExternalStylusButtonState(when);
1578
1579 // Handle policy on initial down or hover events.
1580 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1581 mCurrentRawState.rawPointerData.pointerCount != 0;
1582
1583 uint32_t policyFlags = 0;
1584 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1585 if (initialDown || buttonsPressed) {
1586 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001587 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001588 getContext()->fadePointer();
1589 }
1590
1591 if (mParameters.wake) {
1592 policyFlags |= POLICY_FLAG_WAKE;
1593 }
1594 }
1595
1596 // Consume raw off-screen touches before cooking pointer data.
1597 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001598 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001599 mCurrentRawState.rawPointerData.clear();
1600 }
1601
1602 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1603 // with cooked pointer data that has the same ids and indices as the raw data.
1604 // The following code can use either the raw or cooked data, as needed.
1605 cookPointerData();
1606
1607 // Apply stylus pressure to current cooked state.
1608 applyExternalStylusTouchState(when);
1609
1610 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001611 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1612 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001613 mCurrentCookedState.buttonState);
1614
1615 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001616 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1618 uint32_t id = idBits.clearFirstMarkedBit();
1619 const RawPointerData::Pointer& pointer =
1620 mCurrentRawState.rawPointerData.pointerForId(id);
1621 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1622 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1623 mCurrentCookedState.stylusIdBits.markBit(id);
1624 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1625 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1626 mCurrentCookedState.fingerIdBits.markBit(id);
1627 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1628 mCurrentCookedState.mouseIdBits.markBit(id);
1629 }
1630 }
1631 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1632 uint32_t id = idBits.clearFirstMarkedBit();
1633 const RawPointerData::Pointer& pointer =
1634 mCurrentRawState.rawPointerData.pointerForId(id);
1635 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1636 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1637 mCurrentCookedState.stylusIdBits.markBit(id);
1638 }
1639 }
1640
1641 // Stylus takes precedence over all tools, then mouse, then finger.
1642 PointerUsage pointerUsage = mPointerUsage;
1643 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1644 mCurrentCookedState.mouseIdBits.clear();
1645 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001646 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1648 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001649 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001650 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1651 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001652 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001653 }
1654
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001655 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001656 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001657 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001658
1659 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001660 dispatchButtonRelease(when, readTime, policyFlags);
1661 dispatchHoverExit(when, readTime, policyFlags);
1662 dispatchTouches(when, readTime, policyFlags);
1663 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1664 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001665 }
1666
1667 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1668 mCurrentMotionAborted = false;
1669 }
1670 }
1671
1672 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001673 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001674 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1675 mCurrentCookedState.buttonState);
1676
1677 // Clear some transient state.
1678 mCurrentRawState.rawVScroll = 0;
1679 mCurrentRawState.rawHScroll = 0;
1680
1681 // Copy current touch to last touch in preparation for the next cycle.
1682 mLastRawState.copyFrom(mCurrentRawState);
1683 mLastCookedState.copyFrom(mCurrentCookedState);
1684}
1685
Garfield Tanc734e4f2021-01-15 20:01:39 -08001686void TouchInputMapper::updateTouchSpots() {
1687 if (!mConfig.showTouches || mPointerController == nullptr) {
1688 return;
1689 }
1690
1691 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1692 // clear touch spots.
1693 if (mDeviceMode != DeviceMode::DIRECT &&
1694 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1695 return;
1696 }
1697
1698 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1699 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1700
1701 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001702 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1703 mCurrentCookedState.cookedPointerData.idToIndex,
1704 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001705}
1706
1707bool TouchInputMapper::isTouchScreen() {
1708 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1709 mParameters.hasAssociatedDisplay;
1710}
1711
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001712void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001713 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1715 }
1716}
1717
1718void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1719 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1720 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1721
1722 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1723 float pressure = mExternalStylusState.pressure;
1724 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1725 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1726 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1727 }
1728 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1729 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1730
1731 PointerProperties& properties =
1732 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1733 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1734 properties.toolType = mExternalStylusState.toolType;
1735 }
1736 }
1737}
1738
1739bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001740 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001741 return false;
1742 }
1743
1744 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1745 state.rawPointerData.pointerCount != 0;
1746 if (initialDown) {
1747 if (mExternalStylusState.pressure != 0.0f) {
1748#if DEBUG_STYLUS_FUSION
1749 ALOGD("Have both stylus and touch data, beginning fusion");
1750#endif
1751 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1752 } else if (timeout) {
1753#if DEBUG_STYLUS_FUSION
1754 ALOGD("Timeout expired, assuming touch is not a stylus.");
1755#endif
1756 resetExternalStylus();
1757 } else {
1758 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1759 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1760 }
1761#if DEBUG_STYLUS_FUSION
1762 ALOGD("No stylus data but stylus is connected, requesting timeout "
1763 "(%" PRId64 "ms)",
1764 mExternalStylusFusionTimeout);
1765#endif
1766 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1767 return true;
1768 }
1769 }
1770
1771 // Check if the stylus pointer has gone up.
1772 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1773#if DEBUG_STYLUS_FUSION
1774 ALOGD("Stylus pointer is going up");
1775#endif
1776 mExternalStylusId = -1;
1777 }
1778
1779 return false;
1780}
1781
1782void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001783 if (mDeviceMode == DeviceMode::POINTER) {
1784 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001785 // Since this is a synthetic event, we can consider its latency to be zero
1786 const nsecs_t readTime = when;
1787 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001788 }
Michael Wright227c5542020-07-02 18:30:52 +01001789 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001790 if (mExternalStylusFusionTimeout < when) {
1791 processRawTouches(true /*timeout*/);
1792 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1793 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1794 }
1795 }
1796}
1797
1798void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1799 mExternalStylusState.copyFrom(state);
1800 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1801 // We're either in the middle of a fused stream of data or we're waiting on data before
1802 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1803 // data.
1804 mExternalStylusDataPending = true;
1805 processRawTouches(false /*timeout*/);
1806 }
1807}
1808
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001809bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001810 // Check for release of a virtual key.
1811 if (mCurrentVirtualKey.down) {
1812 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1813 // Pointer went up while virtual key was down.
1814 mCurrentVirtualKey.down = false;
1815 if (!mCurrentVirtualKey.ignored) {
1816#if DEBUG_VIRTUAL_KEYS
1817 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1818 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1819#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001820 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001821 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1822 }
1823 return true;
1824 }
1825
1826 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1827 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1828 const RawPointerData::Pointer& pointer =
1829 mCurrentRawState.rawPointerData.pointerForId(id);
1830 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1831 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1832 // Pointer is still within the space of the virtual key.
1833 return true;
1834 }
1835 }
1836
1837 // Pointer left virtual key area or another pointer also went down.
1838 // Send key cancellation but do not consume the touch yet.
1839 // This is useful when the user swipes through from the virtual key area
1840 // into the main display surface.
1841 mCurrentVirtualKey.down = false;
1842 if (!mCurrentVirtualKey.ignored) {
1843#if DEBUG_VIRTUAL_KEYS
1844 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1845 mCurrentVirtualKey.scanCode);
1846#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001847 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001848 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1849 AKEY_EVENT_FLAG_CANCELED);
1850 }
1851 }
1852
1853 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1854 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1855 // Pointer just went down. Check for virtual key press or off-screen touches.
1856 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1857 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001858 // Exclude unscaled device for inside surface checking.
1859 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001860 // If exactly one pointer went down, check for virtual key hit.
1861 // Otherwise we will drop the entire stroke.
1862 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1863 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1864 if (virtualKey) {
1865 mCurrentVirtualKey.down = true;
1866 mCurrentVirtualKey.downTime = when;
1867 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1868 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1869 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001870 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1871 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001872
1873 if (!mCurrentVirtualKey.ignored) {
1874#if DEBUG_VIRTUAL_KEYS
1875 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1876 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1877#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001878 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001879 AKEY_EVENT_FLAG_FROM_SYSTEM |
1880 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1881 }
1882 }
1883 }
1884 return true;
1885 }
1886 }
1887
1888 // Disable all virtual key touches that happen within a short time interval of the
1889 // most recent touch within the screen area. The idea is to filter out stray
1890 // virtual key presses when interacting with the touch screen.
1891 //
1892 // Problems we're trying to solve:
1893 //
1894 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1895 // virtual key area that is implemented by a separate touch panel and accidentally
1896 // triggers a virtual key.
1897 //
1898 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1899 // area and accidentally triggers a virtual key. This often happens when virtual keys
1900 // are layed out below the screen near to where the on screen keyboard's space bar
1901 // is displayed.
1902 if (mConfig.virtualKeyQuietTime > 0 &&
1903 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001904 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001905 }
1906 return false;
1907}
1908
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001909void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001910 int32_t keyEventAction, int32_t keyEventFlags) {
1911 int32_t keyCode = mCurrentVirtualKey.keyCode;
1912 int32_t scanCode = mCurrentVirtualKey.scanCode;
1913 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001914 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001915 policyFlags |= POLICY_FLAG_VIRTUAL;
1916
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001917 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1918 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1919 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001920 getListener().notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921}
1922
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001923void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1925 if (!currentIdBits.isEmpty()) {
1926 int32_t metaState = getContext()->getGlobalMetaState();
1927 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001928 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1929 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001930 mCurrentCookedState.cookedPointerData.pointerProperties,
1931 mCurrentCookedState.cookedPointerData.pointerCoords,
1932 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1933 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1934 mCurrentMotionAborted = true;
1935 }
1936}
1937
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001938void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001939 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1940 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1941 int32_t metaState = getContext()->getGlobalMetaState();
1942 int32_t buttonState = mCurrentCookedState.buttonState;
1943
1944 if (currentIdBits == lastIdBits) {
1945 if (!currentIdBits.isEmpty()) {
1946 // No pointer id changes so this is a move event.
1947 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001948 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1949 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001950 mCurrentCookedState.cookedPointerData.pointerProperties,
1951 mCurrentCookedState.cookedPointerData.pointerCoords,
1952 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1953 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1954 }
1955 } else {
1956 // There may be pointers going up and pointers going down and pointers moving
1957 // all at the same time.
1958 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1959 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1960 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1961 BitSet32 dispatchedIdBits(lastIdBits.value);
1962
1963 // Update last coordinates of pointers that have moved so that we observe the new
1964 // pointer positions at the same time as other pointers that have just gone up.
1965 bool moveNeeded =
1966 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1967 mCurrentCookedState.cookedPointerData.pointerCoords,
1968 mCurrentCookedState.cookedPointerData.idToIndex,
1969 mLastCookedState.cookedPointerData.pointerProperties,
1970 mLastCookedState.cookedPointerData.pointerCoords,
1971 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1972 if (buttonState != mLastCookedState.buttonState) {
1973 moveNeeded = true;
1974 }
1975
1976 // Dispatch pointer up events.
1977 while (!upIdBits.isEmpty()) {
1978 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001979 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001980 if (isCanceled) {
1981 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1982 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001983 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001984 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001985 mLastCookedState.cookedPointerData.pointerProperties,
1986 mLastCookedState.cookedPointerData.pointerCoords,
1987 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1988 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1989 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001990 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001991 }
1992
1993 // Dispatch move events if any of the remaining pointers moved from their old locations.
1994 // Although applications receive new locations as part of individual pointer up
1995 // events, they do not generally handle them except when presented in a move event.
1996 if (moveNeeded && !moveIdBits.isEmpty()) {
1997 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001998 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1999 metaState, buttonState, 0,
2000 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002001 mCurrentCookedState.cookedPointerData.pointerCoords,
2002 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
2003 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2004 }
2005
2006 // Dispatch pointer down events using the new pointer locations.
2007 while (!downIdBits.isEmpty()) {
2008 uint32_t downId = downIdBits.clearFirstMarkedBit();
2009 dispatchedIdBits.markBit(downId);
2010
2011 if (dispatchedIdBits.count() == 1) {
2012 // First pointer is going down. Set down time.
2013 mDownTime = when;
2014 }
2015
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002016 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2017 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002018 mCurrentCookedState.cookedPointerData.pointerProperties,
2019 mCurrentCookedState.cookedPointerData.pointerCoords,
2020 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
2021 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2022 }
2023 }
2024}
2025
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002026void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002027 if (mSentHoverEnter &&
2028 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2029 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2030 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002031 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2032 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002033 mLastCookedState.cookedPointerData.pointerProperties,
2034 mLastCookedState.cookedPointerData.pointerCoords,
2035 mLastCookedState.cookedPointerData.idToIndex,
2036 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2037 mOrientedYPrecision, mDownTime);
2038 mSentHoverEnter = false;
2039 }
2040}
2041
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002042void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2043 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002044 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2045 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2046 int32_t metaState = getContext()->getGlobalMetaState();
2047 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002048 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2049 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002050 mCurrentCookedState.cookedPointerData.pointerProperties,
2051 mCurrentCookedState.cookedPointerData.pointerCoords,
2052 mCurrentCookedState.cookedPointerData.idToIndex,
2053 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2054 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2055 mSentHoverEnter = true;
2056 }
2057
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002058 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2059 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002060 mCurrentCookedState.cookedPointerData.pointerProperties,
2061 mCurrentCookedState.cookedPointerData.pointerCoords,
2062 mCurrentCookedState.cookedPointerData.idToIndex,
2063 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2064 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2065 }
2066}
2067
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002068void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002069 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2070 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2071 const int32_t metaState = getContext()->getGlobalMetaState();
2072 int32_t buttonState = mLastCookedState.buttonState;
2073 while (!releasedButtons.isEmpty()) {
2074 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2075 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002076 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002077 actionButton, 0, metaState, buttonState, 0,
2078 mCurrentCookedState.cookedPointerData.pointerProperties,
2079 mCurrentCookedState.cookedPointerData.pointerCoords,
2080 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2081 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2082 }
2083}
2084
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002085void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002086 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2087 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2088 const int32_t metaState = getContext()->getGlobalMetaState();
2089 int32_t buttonState = mLastCookedState.buttonState;
2090 while (!pressedButtons.isEmpty()) {
2091 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2092 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002093 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2094 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002095 mCurrentCookedState.cookedPointerData.pointerProperties,
2096 mCurrentCookedState.cookedPointerData.pointerCoords,
2097 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2098 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2099 }
2100}
2101
2102const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2103 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2104 return cookedPointerData.touchingIdBits;
2105 }
2106 return cookedPointerData.hoveringIdBits;
2107}
2108
2109void TouchInputMapper::cookPointerData() {
2110 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2111
2112 mCurrentCookedState.cookedPointerData.clear();
2113 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2114 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2115 mCurrentRawState.rawPointerData.hoveringIdBits;
2116 mCurrentCookedState.cookedPointerData.touchingIdBits =
2117 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002118 mCurrentCookedState.cookedPointerData.canceledIdBits =
2119 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002120
2121 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2122 mCurrentCookedState.buttonState = 0;
2123 } else {
2124 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2125 }
2126
2127 // Walk through the the active pointers and map device coordinates onto
2128 // surface coordinates and adjust for display orientation.
2129 for (uint32_t i = 0; i < currentPointerCount; i++) {
2130 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2131
2132 // Size
2133 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2134 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002135 case Calibration::SizeCalibration::GEOMETRIC:
2136 case Calibration::SizeCalibration::DIAMETER:
2137 case Calibration::SizeCalibration::BOX:
2138 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002139 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2140 touchMajor = in.touchMajor;
2141 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2142 toolMajor = in.toolMajor;
2143 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2144 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2145 : in.touchMajor;
2146 } else if (mRawPointerAxes.touchMajor.valid) {
2147 toolMajor = touchMajor = in.touchMajor;
2148 toolMinor = touchMinor =
2149 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2150 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2151 : in.touchMajor;
2152 } else if (mRawPointerAxes.toolMajor.valid) {
2153 touchMajor = toolMajor = in.toolMajor;
2154 touchMinor = toolMinor =
2155 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2156 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2157 : in.toolMajor;
2158 } else {
2159 ALOG_ASSERT(false,
2160 "No touch or tool axes. "
2161 "Size calibration should have been resolved to NONE.");
2162 touchMajor = 0;
2163 touchMinor = 0;
2164 toolMajor = 0;
2165 toolMinor = 0;
2166 size = 0;
2167 }
2168
2169 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2170 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2171 if (touchingCount > 1) {
2172 touchMajor /= touchingCount;
2173 touchMinor /= touchingCount;
2174 toolMajor /= touchingCount;
2175 toolMinor /= touchingCount;
2176 size /= touchingCount;
2177 }
2178 }
2179
Michael Wright227c5542020-07-02 18:30:52 +01002180 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002181 touchMajor *= mGeometricScale;
2182 touchMinor *= mGeometricScale;
2183 toolMajor *= mGeometricScale;
2184 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002185 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002186 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2187 touchMinor = touchMajor;
2188 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2189 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002190 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002191 touchMinor = touchMajor;
2192 toolMinor = toolMajor;
2193 }
2194
2195 mCalibration.applySizeScaleAndBias(&touchMajor);
2196 mCalibration.applySizeScaleAndBias(&touchMinor);
2197 mCalibration.applySizeScaleAndBias(&toolMajor);
2198 mCalibration.applySizeScaleAndBias(&toolMinor);
2199 size *= mSizeScale;
2200 break;
2201 default:
2202 touchMajor = 0;
2203 touchMinor = 0;
2204 toolMajor = 0;
2205 toolMinor = 0;
2206 size = 0;
2207 break;
2208 }
2209
2210 // Pressure
2211 float pressure;
2212 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002213 case Calibration::PressureCalibration::PHYSICAL:
2214 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002215 pressure = in.pressure * mPressureScale;
2216 break;
2217 default:
2218 pressure = in.isHovering ? 0 : 1;
2219 break;
2220 }
2221
2222 // Tilt and Orientation
2223 float tilt;
2224 float orientation;
2225 if (mHaveTilt) {
2226 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2227 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2228 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2229 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2230 } else {
2231 tilt = 0;
2232
2233 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002234 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002235 orientation = in.orientation * mOrientationScale;
2236 break;
Michael Wright227c5542020-07-02 18:30:52 +01002237 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002238 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2239 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2240 if (c1 != 0 || c2 != 0) {
2241 orientation = atan2f(c1, c2) * 0.5f;
2242 float confidence = hypotf(c1, c2);
2243 float scale = 1.0f + confidence / 16.0f;
2244 touchMajor *= scale;
2245 touchMinor /= scale;
2246 toolMajor *= scale;
2247 toolMinor /= scale;
2248 } else {
2249 orientation = 0;
2250 }
2251 break;
2252 }
2253 default:
2254 orientation = 0;
2255 }
2256 }
2257
2258 // Distance
2259 float distance;
2260 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002261 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002262 distance = in.distance * mDistanceScale;
2263 break;
2264 default:
2265 distance = 0;
2266 }
2267
2268 // Coverage
2269 int32_t rawLeft, rawTop, rawRight, rawBottom;
2270 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002271 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002272 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2273 rawRight = in.toolMinor & 0x0000ffff;
2274 rawBottom = in.toolMajor & 0x0000ffff;
2275 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2276 break;
2277 default:
2278 rawLeft = rawTop = rawRight = rawBottom = 0;
2279 break;
2280 }
2281
2282 // Adjust X,Y coords for device calibration
2283 // TODO: Adjust coverage coords?
2284 float xTransformed = in.x, yTransformed = in.y;
2285 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002286 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002287
2288 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002289 float left, top, right, bottom;
2290
2291 switch (mSurfaceOrientation) {
2292 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002293 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2294 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2295 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2296 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2297 orientation -= M_PI_2;
2298 if (mOrientedRanges.haveOrientation &&
2299 orientation < mOrientedRanges.orientation.min) {
2300 orientation +=
2301 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2302 }
2303 break;
2304 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002305 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2306 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2307 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2308 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2309 orientation -= M_PI;
2310 if (mOrientedRanges.haveOrientation &&
2311 orientation < mOrientedRanges.orientation.min) {
2312 orientation +=
2313 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2314 }
2315 break;
2316 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2318 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2319 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2320 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2321 orientation += M_PI_2;
2322 if (mOrientedRanges.haveOrientation &&
2323 orientation > mOrientedRanges.orientation.max) {
2324 orientation -=
2325 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2326 }
2327 break;
2328 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002329 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2330 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2331 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2332 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2333 break;
2334 }
2335
2336 // Write output coords.
2337 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2338 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002339 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2340 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002341 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2342 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2343 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2344 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2345 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2346 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2347 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002348 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2350 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2351 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2352 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2353 } else {
2354 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2355 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2356 }
2357
Chris Ye364fdb52020-08-05 15:07:56 -07002358 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002359 uint32_t id = in.id;
2360 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2361 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2362 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2363 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2364 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2365 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2366 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2367 }
2368
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 // Write output properties.
2370 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 properties.clear();
2372 properties.id = id;
2373 properties.toolType = in.toolType;
2374
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002375 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002376 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002377 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 }
2379}
2380
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002381void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 PointerUsage pointerUsage) {
2383 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002384 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 mPointerUsage = pointerUsage;
2386 }
2387
2388 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002389 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002390 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 break;
Michael Wright227c5542020-07-02 18:30:52 +01002392 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002393 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 break;
Michael Wright227c5542020-07-02 18:30:52 +01002395 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002396 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 break;
Michael Wright227c5542020-07-02 18:30:52 +01002398 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002399 break;
2400 }
2401}
2402
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002403void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002405 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002406 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002407 break;
Michael Wright227c5542020-07-02 18:30:52 +01002408 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002409 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 break;
Michael Wright227c5542020-07-02 18:30:52 +01002411 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002412 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002413 break;
Michael Wright227c5542020-07-02 18:30:52 +01002414 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 break;
2416 }
2417
Michael Wright227c5542020-07-02 18:30:52 +01002418 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419}
2420
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002421void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2422 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002423 // Update current gesture coordinates.
2424 bool cancelPreviousGesture, finishPreviousGesture;
2425 bool sendEvents =
2426 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2427 if (!sendEvents) {
2428 return;
2429 }
2430 if (finishPreviousGesture) {
2431 cancelPreviousGesture = false;
2432 }
2433
2434 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002435 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002436 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002437 if (finishPreviousGesture || cancelPreviousGesture) {
2438 mPointerController->clearSpots();
2439 }
2440
Michael Wright227c5542020-07-02 18:30:52 +01002441 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002442 setTouchSpots(mPointerGesture.currentGestureCoords,
2443 mPointerGesture.currentGestureIdToIndex,
2444 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 }
2446 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002447 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 }
2449
2450 // Show or hide the pointer if needed.
2451 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002452 case PointerGesture::Mode::NEUTRAL:
2453 case PointerGesture::Mode::QUIET:
2454 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2455 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002457 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 }
2459 break;
Michael Wright227c5542020-07-02 18:30:52 +01002460 case PointerGesture::Mode::TAP:
2461 case PointerGesture::Mode::TAP_DRAG:
2462 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2463 case PointerGesture::Mode::HOVER:
2464 case PointerGesture::Mode::PRESS:
2465 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 // Unfade the pointer when the current gesture manipulates the
2467 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002468 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 break;
Michael Wright227c5542020-07-02 18:30:52 +01002470 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002471 // Fade the pointer when the current gesture manipulates a different
2472 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002473 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002474 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002476 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002477 }
2478 break;
2479 }
2480
2481 // Send events!
2482 int32_t metaState = getContext()->getGlobalMetaState();
2483 int32_t buttonState = mCurrentCookedState.buttonState;
2484
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002485 uint32_t flags = 0;
2486
2487 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2488 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2489 }
2490
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491 // Update last coordinates of pointers that have moved so that we observe the new
2492 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002493 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2494 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2495 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2496 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2497 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2498 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002499 bool moveNeeded = false;
2500 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2501 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2502 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2503 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2504 mPointerGesture.lastGestureIdBits.value);
2505 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2506 mPointerGesture.currentGestureCoords,
2507 mPointerGesture.currentGestureIdToIndex,
2508 mPointerGesture.lastGestureProperties,
2509 mPointerGesture.lastGestureCoords,
2510 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2511 if (buttonState != mLastCookedState.buttonState) {
2512 moveNeeded = true;
2513 }
2514 }
2515
2516 // Send motion events for all pointers that went up or were canceled.
2517 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2518 if (!dispatchedGestureIdBits.isEmpty()) {
2519 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002520 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2521 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2523 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2524 mPointerGesture.downTime);
2525
2526 dispatchedGestureIdBits.clear();
2527 } else {
2528 BitSet32 upGestureIdBits;
2529 if (finishPreviousGesture) {
2530 upGestureIdBits = dispatchedGestureIdBits;
2531 } else {
2532 upGestureIdBits.value =
2533 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2534 }
2535 while (!upGestureIdBits.isEmpty()) {
2536 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2537
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002538 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002539 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002540 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541 mPointerGesture.lastGestureCoords,
2542 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2543 0, mPointerGesture.downTime);
2544
2545 dispatchedGestureIdBits.clearBit(id);
2546 }
2547 }
2548 }
2549
2550 // Send motion events for all pointers that moved.
2551 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002552 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002553 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002554 mPointerGesture.currentGestureProperties,
2555 mPointerGesture.currentGestureCoords,
2556 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2557 mPointerGesture.downTime);
2558 }
2559
2560 // Send motion events for all pointers that went down.
2561 if (down) {
2562 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2563 ~dispatchedGestureIdBits.value);
2564 while (!downGestureIdBits.isEmpty()) {
2565 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2566 dispatchedGestureIdBits.markBit(id);
2567
2568 if (dispatchedGestureIdBits.count() == 1) {
2569 mPointerGesture.downTime = when;
2570 }
2571
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002572 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002573 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002574 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002575 mPointerGesture.currentGestureCoords,
2576 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2577 0, mPointerGesture.downTime);
2578 }
2579 }
2580
2581 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002582 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002583 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2584 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002585 mPointerGesture.currentGestureProperties,
2586 mPointerGesture.currentGestureCoords,
2587 mPointerGesture.currentGestureIdToIndex,
2588 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2589 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2590 // Synthesize a hover move event after all pointers go up to indicate that
2591 // the pointer is hovering again even if the user is not currently touching
2592 // the touch pad. This ensures that a view will receive a fresh hover enter
2593 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002594 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002595
2596 PointerProperties pointerProperties;
2597 pointerProperties.clear();
2598 pointerProperties.id = 0;
2599 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2600
2601 PointerCoords pointerCoords;
2602 pointerCoords.clear();
2603 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2604 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2605
2606 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002607 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002608 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002609 metaState, buttonState, MotionClassification::NONE,
2610 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2611 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002612 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002613 }
2614
2615 // Update state.
2616 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2617 if (!down) {
2618 mPointerGesture.lastGestureIdBits.clear();
2619 } else {
2620 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2621 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2622 uint32_t id = idBits.clearFirstMarkedBit();
2623 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2624 mPointerGesture.lastGestureProperties[index].copyFrom(
2625 mPointerGesture.currentGestureProperties[index]);
2626 mPointerGesture.lastGestureCoords[index].copyFrom(
2627 mPointerGesture.currentGestureCoords[index]);
2628 mPointerGesture.lastGestureIdToIndex[id] = index;
2629 }
2630 }
2631}
2632
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002633void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002634 // Cancel previously dispatches pointers.
2635 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2636 int32_t metaState = getContext()->getGlobalMetaState();
2637 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002638 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2639 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002640 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2641 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2642 0, 0, mPointerGesture.downTime);
2643 }
2644
2645 // Reset the current pointer gesture.
2646 mPointerGesture.reset();
2647 mPointerVelocityControl.reset();
2648
2649 // Remove any current spots.
2650 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002651 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002652 mPointerController->clearSpots();
2653 }
2654}
2655
2656bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2657 bool* outFinishPreviousGesture, bool isTimeout) {
2658 *outCancelPreviousGesture = false;
2659 *outFinishPreviousGesture = false;
2660
2661 // Handle TAP timeout.
2662 if (isTimeout) {
2663#if DEBUG_GESTURES
2664 ALOGD("Gestures: Processing timeout");
2665#endif
2666
Michael Wright227c5542020-07-02 18:30:52 +01002667 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002668 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2669 // The tap/drag timeout has not yet expired.
2670 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2671 mConfig.pointerGestureTapDragInterval);
2672 } else {
2673 // The tap is finished.
2674#if DEBUG_GESTURES
2675 ALOGD("Gestures: TAP finished");
2676#endif
2677 *outFinishPreviousGesture = true;
2678
2679 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002680 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002681 mPointerGesture.currentGestureIdBits.clear();
2682
2683 mPointerVelocityControl.reset();
2684 return true;
2685 }
2686 }
2687
2688 // We did not handle this timeout.
2689 return false;
2690 }
2691
2692 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2693 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2694
2695 // Update the velocity tracker.
2696 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002697 std::vector<VelocityTracker::Position> positions;
2698 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002699 uint32_t id = idBits.clearFirstMarkedBit();
2700 const RawPointerData::Pointer& pointer =
2701 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002702 float x = pointer.x * mPointerXMovementScale;
2703 float y = pointer.y * mPointerYMovementScale;
2704 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002705 }
2706 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2707 positions);
2708 }
2709
2710 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2711 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002712 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2713 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2714 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002715 mPointerGesture.resetTap();
2716 }
2717
2718 // Pick a new active touch id if needed.
2719 // Choose an arbitrary pointer that just went down, if there is one.
2720 // Otherwise choose an arbitrary remaining pointer.
2721 // This guarantees we always have an active touch id when there is at least one pointer.
2722 // We keep the same active touch id for as long as possible.
2723 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2724 int32_t activeTouchId = lastActiveTouchId;
2725 if (activeTouchId < 0) {
2726 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2727 activeTouchId = mPointerGesture.activeTouchId =
2728 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2729 mPointerGesture.firstTouchTime = when;
2730 }
2731 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2732 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2733 activeTouchId = mPointerGesture.activeTouchId =
2734 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2735 } else {
2736 activeTouchId = mPointerGesture.activeTouchId = -1;
2737 }
2738 }
2739
2740 // Determine whether we are in quiet time.
2741 bool isQuietTime = false;
2742 if (activeTouchId < 0) {
2743 mPointerGesture.resetQuietTime();
2744 } else {
2745 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2746 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002747 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2748 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2749 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002750 currentFingerCount < 2) {
2751 // Enter quiet time when exiting swipe or freeform state.
2752 // This is to prevent accidentally entering the hover state and flinging the
2753 // pointer when finishing a swipe and there is still one pointer left onscreen.
2754 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002755 } else if (mPointerGesture.lastGestureMode ==
2756 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002757 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2758 // Enter quiet time when releasing the button and there are still two or more
2759 // fingers down. This may indicate that one finger was used to press the button
2760 // but it has not gone up yet.
2761 isQuietTime = true;
2762 }
2763 if (isQuietTime) {
2764 mPointerGesture.quietTime = when;
2765 }
2766 }
2767 }
2768
2769 // Switch states based on button and pointer state.
2770 if (isQuietTime) {
2771 // Case 1: Quiet time. (QUIET)
2772#if DEBUG_GESTURES
2773 ALOGD("Gestures: QUIET for next %0.3fms",
2774 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2775#endif
Michael Wright227c5542020-07-02 18:30:52 +01002776 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002777 *outFinishPreviousGesture = true;
2778 }
2779
2780 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002781 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002782 mPointerGesture.currentGestureIdBits.clear();
2783
2784 mPointerVelocityControl.reset();
2785 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2786 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2787 // The pointer follows the active touch point.
2788 // Emit DOWN, MOVE, UP events at the pointer location.
2789 //
2790 // Only the active touch matters; other fingers are ignored. This policy helps
2791 // to handle the case where the user places a second finger on the touch pad
2792 // to apply the necessary force to depress an integrated button below the surface.
2793 // We don't want the second finger to be delivered to applications.
2794 //
2795 // For this to work well, we need to make sure to track the pointer that is really
2796 // active. If the user first puts one finger down to click then adds another
2797 // finger to drag then the active pointer should switch to the finger that is
2798 // being dragged.
2799#if DEBUG_GESTURES
2800 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2801 "currentFingerCount=%d",
2802 activeTouchId, currentFingerCount);
2803#endif
2804 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002805 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 *outFinishPreviousGesture = true;
2807 mPointerGesture.activeGestureId = 0;
2808 }
2809
2810 // Switch pointers if needed.
2811 // Find the fastest pointer and follow it.
2812 if (activeTouchId >= 0 && currentFingerCount > 1) {
2813 int32_t bestId = -1;
2814 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2815 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2816 uint32_t id = idBits.clearFirstMarkedBit();
2817 float vx, vy;
2818 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2819 float speed = hypotf(vx, vy);
2820 if (speed > bestSpeed) {
2821 bestId = id;
2822 bestSpeed = speed;
2823 }
2824 }
2825 }
2826 if (bestId >= 0 && bestId != activeTouchId) {
2827 mPointerGesture.activeTouchId = activeTouchId = bestId;
2828#if DEBUG_GESTURES
2829 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2830 "bestId=%d, bestSpeed=%0.3f",
2831 bestId, bestSpeed);
2832#endif
2833 }
2834 }
2835
2836 float deltaX = 0, deltaY = 0;
2837 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2838 const RawPointerData::Pointer& currentPointer =
2839 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2840 const RawPointerData::Pointer& lastPointer =
2841 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2842 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2843 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2844
2845 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2846 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2847
2848 // Move the pointer using a relative motion.
2849 // When using spots, the click will occur at the position of the anchor
2850 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002851 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002852 } else {
2853 mPointerVelocityControl.reset();
2854 }
2855
Prabir Pradhand7482e72021-03-09 13:54:55 -08002856 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857
Michael Wright227c5542020-07-02 18:30:52 +01002858 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859 mPointerGesture.currentGestureIdBits.clear();
2860 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2861 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2862 mPointerGesture.currentGestureProperties[0].clear();
2863 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2864 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2865 mPointerGesture.currentGestureCoords[0].clear();
2866 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2867 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2868 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2869 } else if (currentFingerCount == 0) {
2870 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002871 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 *outFinishPreviousGesture = true;
2873 }
2874
2875 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2876 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2877 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002878 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2879 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002880 lastFingerCount == 1) {
2881 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002882 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002883 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2884 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2885#if DEBUG_GESTURES
2886 ALOGD("Gestures: TAP");
2887#endif
2888
2889 mPointerGesture.tapUpTime = when;
2890 getContext()->requestTimeoutAtTime(when +
2891 mConfig.pointerGestureTapDragInterval);
2892
2893 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002894 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 mPointerGesture.currentGestureIdBits.clear();
2896 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2897 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2898 mPointerGesture.currentGestureProperties[0].clear();
2899 mPointerGesture.currentGestureProperties[0].id =
2900 mPointerGesture.activeGestureId;
2901 mPointerGesture.currentGestureProperties[0].toolType =
2902 AMOTION_EVENT_TOOL_TYPE_FINGER;
2903 mPointerGesture.currentGestureCoords[0].clear();
2904 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2905 mPointerGesture.tapX);
2906 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2907 mPointerGesture.tapY);
2908 mPointerGesture.currentGestureCoords[0]
2909 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2910
2911 tapped = true;
2912 } else {
2913#if DEBUG_GESTURES
2914 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2915 y - mPointerGesture.tapY);
2916#endif
2917 }
2918 } else {
2919#if DEBUG_GESTURES
2920 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2921 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2922 (when - mPointerGesture.tapDownTime) * 0.000001f);
2923 } else {
2924 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2925 }
2926#endif
2927 }
2928 }
2929
2930 mPointerVelocityControl.reset();
2931
2932 if (!tapped) {
2933#if DEBUG_GESTURES
2934 ALOGD("Gestures: NEUTRAL");
2935#endif
2936 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002937 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002938 mPointerGesture.currentGestureIdBits.clear();
2939 }
2940 } else if (currentFingerCount == 1) {
2941 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2942 // The pointer follows the active touch point.
2943 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2944 // When in TAP_DRAG, emit MOVE events at the pointer location.
2945 ALOG_ASSERT(activeTouchId >= 0);
2946
Michael Wright227c5542020-07-02 18:30:52 +01002947 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2948 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002949 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002950 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2952 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002953 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 } else {
2955#if DEBUG_GESTURES
2956 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2957 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2958#endif
2959 }
2960 } else {
2961#if DEBUG_GESTURES
2962 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2963 (when - mPointerGesture.tapUpTime) * 0.000001f);
2964#endif
2965 }
Michael Wright227c5542020-07-02 18:30:52 +01002966 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2967 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 }
2969
2970 float deltaX = 0, deltaY = 0;
2971 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2972 const RawPointerData::Pointer& currentPointer =
2973 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2974 const RawPointerData::Pointer& lastPointer =
2975 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2976 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2977 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2978
2979 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2980 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2981
2982 // Move the pointer using a relative motion.
2983 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002984 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002985 } else {
2986 mPointerVelocityControl.reset();
2987 }
2988
2989 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002990 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991#if DEBUG_GESTURES
2992 ALOGD("Gestures: TAP_DRAG");
2993#endif
2994 down = true;
2995 } else {
2996#if DEBUG_GESTURES
2997 ALOGD("Gestures: HOVER");
2998#endif
Michael Wright227c5542020-07-02 18:30:52 +01002999 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003000 *outFinishPreviousGesture = true;
3001 }
3002 mPointerGesture.activeGestureId = 0;
3003 down = false;
3004 }
3005
Prabir Pradhand7482e72021-03-09 13:54:55 -08003006 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003007
3008 mPointerGesture.currentGestureIdBits.clear();
3009 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3010 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3011 mPointerGesture.currentGestureProperties[0].clear();
3012 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3013 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3014 mPointerGesture.currentGestureCoords[0].clear();
3015 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3016 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3017 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3018 down ? 1.0f : 0.0f);
3019
3020 if (lastFingerCount == 0 && currentFingerCount != 0) {
3021 mPointerGesture.resetTap();
3022 mPointerGesture.tapDownTime = when;
3023 mPointerGesture.tapX = x;
3024 mPointerGesture.tapY = y;
3025 }
3026 } else {
3027 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3028 // We need to provide feedback for each finger that goes down so we cannot wait
3029 // for the fingers to move before deciding what to do.
3030 //
3031 // The ambiguous case is deciding what to do when there are two fingers down but they
3032 // have not moved enough to determine whether they are part of a drag or part of a
3033 // freeform gesture, or just a press or long-press at the pointer location.
3034 //
3035 // When there are two fingers we start with the PRESS hypothesis and we generate a
3036 // down at the pointer location.
3037 //
3038 // When the two fingers move enough or when additional fingers are added, we make
3039 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3040 ALOG_ASSERT(activeTouchId >= 0);
3041
3042 bool settled = when >=
3043 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003044 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3045 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3046 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047 *outFinishPreviousGesture = true;
3048 } else if (!settled && currentFingerCount > lastFingerCount) {
3049 // Additional pointers have gone down but not yet settled.
3050 // Reset the gesture.
3051#if DEBUG_GESTURES
3052 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3053 "settle time remaining %0.3fms",
3054 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3055 when) * 0.000001f);
3056#endif
3057 *outCancelPreviousGesture = true;
3058 } else {
3059 // Continue previous gesture.
3060 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3061 }
3062
3063 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003064 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003065 mPointerGesture.activeGestureId = 0;
3066 mPointerGesture.referenceIdBits.clear();
3067 mPointerVelocityControl.reset();
3068
3069 // Use the centroid and pointer location as the reference points for the gesture.
3070#if DEBUG_GESTURES
3071 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3072 "settle time remaining %0.3fms",
3073 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3074 when) * 0.000001f);
3075#endif
3076 mCurrentRawState.rawPointerData
3077 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3078 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003079 auto [x, y] = getMouseCursorPosition();
3080 mPointerGesture.referenceGestureX = x;
3081 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003082 }
3083
3084 // Clear the reference deltas for fingers not yet included in the reference calculation.
3085 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3086 ~mPointerGesture.referenceIdBits.value);
3087 !idBits.isEmpty();) {
3088 uint32_t id = idBits.clearFirstMarkedBit();
3089 mPointerGesture.referenceDeltas[id].dx = 0;
3090 mPointerGesture.referenceDeltas[id].dy = 0;
3091 }
3092 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3093
3094 // Add delta for all fingers and calculate a common movement delta.
3095 float commonDeltaX = 0, commonDeltaY = 0;
3096 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3097 mCurrentCookedState.fingerIdBits.value);
3098 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3099 bool first = (idBits == commonIdBits);
3100 uint32_t id = idBits.clearFirstMarkedBit();
3101 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3102 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3103 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3104 delta.dx += cpd.x - lpd.x;
3105 delta.dy += cpd.y - lpd.y;
3106
3107 if (first) {
3108 commonDeltaX = delta.dx;
3109 commonDeltaY = delta.dy;
3110 } else {
3111 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3112 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3113 }
3114 }
3115
3116 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003117 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003118 float dist[MAX_POINTER_ID + 1];
3119 int32_t distOverThreshold = 0;
3120 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3121 uint32_t id = idBits.clearFirstMarkedBit();
3122 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3123 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3124 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3125 distOverThreshold += 1;
3126 }
3127 }
3128
3129 // Only transition when at least two pointers have moved further than
3130 // the minimum distance threshold.
3131 if (distOverThreshold >= 2) {
3132 if (currentFingerCount > 2) {
3133 // There are more than two pointers, switch to FREEFORM.
3134#if DEBUG_GESTURES
3135 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3136 currentFingerCount);
3137#endif
3138 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003139 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003140 } else {
3141 // There are exactly two pointers.
3142 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3143 uint32_t id1 = idBits.clearFirstMarkedBit();
3144 uint32_t id2 = idBits.firstMarkedBit();
3145 const RawPointerData::Pointer& p1 =
3146 mCurrentRawState.rawPointerData.pointerForId(id1);
3147 const RawPointerData::Pointer& p2 =
3148 mCurrentRawState.rawPointerData.pointerForId(id2);
3149 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3150 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3151 // There are two pointers but they are too far apart for a SWIPE,
3152 // switch to FREEFORM.
3153#if DEBUG_GESTURES
3154 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3155 mutualDistance, mPointerGestureMaxSwipeWidth);
3156#endif
3157 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003158 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003159 } else {
3160 // There are two pointers. Wait for both pointers to start moving
3161 // before deciding whether this is a SWIPE or FREEFORM gesture.
3162 float dist1 = dist[id1];
3163 float dist2 = dist[id2];
3164 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3165 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3166 // Calculate the dot product of the displacement vectors.
3167 // When the vectors are oriented in approximately the same direction,
3168 // the angle betweeen them is near zero and the cosine of the angle
3169 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3170 // mag(v2).
3171 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3172 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3173 float dx1 = delta1.dx * mPointerXZoomScale;
3174 float dy1 = delta1.dy * mPointerYZoomScale;
3175 float dx2 = delta2.dx * mPointerXZoomScale;
3176 float dy2 = delta2.dy * mPointerYZoomScale;
3177 float dot = dx1 * dx2 + dy1 * dy2;
3178 float cosine = dot / (dist1 * dist2); // denominator always > 0
3179 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3180 // Pointers are moving in the same direction. Switch to SWIPE.
3181#if DEBUG_GESTURES
3182 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3183 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3184 "cosine %0.3f >= %0.3f",
3185 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3186 mConfig.pointerGestureMultitouchMinDistance, cosine,
3187 mConfig.pointerGestureSwipeTransitionAngleCosine);
3188#endif
Michael Wright227c5542020-07-02 18:30:52 +01003189 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003190 } else {
3191 // Pointers are moving in different directions. Switch to FREEFORM.
3192#if DEBUG_GESTURES
3193 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3194 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3195 "cosine %0.3f < %0.3f",
3196 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3197 mConfig.pointerGestureMultitouchMinDistance, cosine,
3198 mConfig.pointerGestureSwipeTransitionAngleCosine);
3199#endif
3200 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003201 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003202 }
3203 }
3204 }
3205 }
3206 }
Michael Wright227c5542020-07-02 18:30:52 +01003207 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003208 // Switch from SWIPE to FREEFORM if additional pointers go down.
3209 // Cancel previous gesture.
3210 if (currentFingerCount > 2) {
3211#if DEBUG_GESTURES
3212 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3213 currentFingerCount);
3214#endif
3215 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003216 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003217 }
3218 }
3219
3220 // Move the reference points based on the overall group motion of the fingers
3221 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003222 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003223 (commonDeltaX || commonDeltaY)) {
3224 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3225 uint32_t id = idBits.clearFirstMarkedBit();
3226 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3227 delta.dx = 0;
3228 delta.dy = 0;
3229 }
3230
3231 mPointerGesture.referenceTouchX += commonDeltaX;
3232 mPointerGesture.referenceTouchY += commonDeltaY;
3233
3234 commonDeltaX *= mPointerXMovementScale;
3235 commonDeltaY *= mPointerYMovementScale;
3236
3237 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3238 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3239
3240 mPointerGesture.referenceGestureX += commonDeltaX;
3241 mPointerGesture.referenceGestureY += commonDeltaY;
3242 }
3243
3244 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003245 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3246 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003247 // PRESS or SWIPE mode.
3248#if DEBUG_GESTURES
3249 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3250 "activeGestureId=%d, currentTouchPointerCount=%d",
3251 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3252#endif
3253 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3254
3255 mPointerGesture.currentGestureIdBits.clear();
3256 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3257 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3258 mPointerGesture.currentGestureProperties[0].clear();
3259 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3260 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3261 mPointerGesture.currentGestureCoords[0].clear();
3262 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3263 mPointerGesture.referenceGestureX);
3264 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3265 mPointerGesture.referenceGestureY);
3266 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003267 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003268 // FREEFORM mode.
3269#if DEBUG_GESTURES
3270 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3271 "activeGestureId=%d, currentTouchPointerCount=%d",
3272 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3273#endif
3274 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3275
3276 mPointerGesture.currentGestureIdBits.clear();
3277
3278 BitSet32 mappedTouchIdBits;
3279 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003280 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003281 // Initially, assign the active gesture id to the active touch point
3282 // if there is one. No other touch id bits are mapped yet.
3283 if (!*outCancelPreviousGesture) {
3284 mappedTouchIdBits.markBit(activeTouchId);
3285 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3286 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3287 mPointerGesture.activeGestureId;
3288 } else {
3289 mPointerGesture.activeGestureId = -1;
3290 }
3291 } else {
3292 // Otherwise, assume we mapped all touches from the previous frame.
3293 // Reuse all mappings that are still applicable.
3294 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3295 mCurrentCookedState.fingerIdBits.value;
3296 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3297
3298 // Check whether we need to choose a new active gesture id because the
3299 // current went went up.
3300 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3301 ~mCurrentCookedState.fingerIdBits.value);
3302 !upTouchIdBits.isEmpty();) {
3303 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3304 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3305 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3306 mPointerGesture.activeGestureId = -1;
3307 break;
3308 }
3309 }
3310 }
3311
3312#if DEBUG_GESTURES
3313 ALOGD("Gestures: FREEFORM follow up "
3314 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3315 "activeGestureId=%d",
3316 mappedTouchIdBits.value, usedGestureIdBits.value,
3317 mPointerGesture.activeGestureId);
3318#endif
3319
3320 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3321 for (uint32_t i = 0; i < currentFingerCount; i++) {
3322 uint32_t touchId = idBits.clearFirstMarkedBit();
3323 uint32_t gestureId;
3324 if (!mappedTouchIdBits.hasBit(touchId)) {
3325 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3326 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3327#if DEBUG_GESTURES
3328 ALOGD("Gestures: FREEFORM "
3329 "new mapping for touch id %d -> gesture id %d",
3330 touchId, gestureId);
3331#endif
3332 } else {
3333 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3334#if DEBUG_GESTURES
3335 ALOGD("Gestures: FREEFORM "
3336 "existing mapping for touch id %d -> gesture id %d",
3337 touchId, gestureId);
3338#endif
3339 }
3340 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3341 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3342
3343 const RawPointerData::Pointer& pointer =
3344 mCurrentRawState.rawPointerData.pointerForId(touchId);
3345 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3346 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3347 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3348
3349 mPointerGesture.currentGestureProperties[i].clear();
3350 mPointerGesture.currentGestureProperties[i].id = gestureId;
3351 mPointerGesture.currentGestureProperties[i].toolType =
3352 AMOTION_EVENT_TOOL_TYPE_FINGER;
3353 mPointerGesture.currentGestureCoords[i].clear();
3354 mPointerGesture.currentGestureCoords[i]
3355 .setAxisValue(AMOTION_EVENT_AXIS_X,
3356 mPointerGesture.referenceGestureX + deltaX);
3357 mPointerGesture.currentGestureCoords[i]
3358 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3359 mPointerGesture.referenceGestureY + deltaY);
3360 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3361 1.0f);
3362 }
3363
3364 if (mPointerGesture.activeGestureId < 0) {
3365 mPointerGesture.activeGestureId =
3366 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3367#if DEBUG_GESTURES
3368 ALOGD("Gestures: FREEFORM new "
3369 "activeGestureId=%d",
3370 mPointerGesture.activeGestureId);
3371#endif
3372 }
3373 }
3374 }
3375
3376 mPointerController->setButtonState(mCurrentRawState.buttonState);
3377
3378#if DEBUG_GESTURES
3379 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3380 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3381 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3382 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3383 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3384 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3385 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3386 uint32_t id = idBits.clearFirstMarkedBit();
3387 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3388 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3389 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3390 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3391 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3392 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3393 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3394 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3395 }
3396 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3397 uint32_t id = idBits.clearFirstMarkedBit();
3398 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3399 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3400 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3401 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3402 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3403 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3404 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3405 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3406 }
3407#endif
3408 return true;
3409}
3410
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003411void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003412 mPointerSimple.currentCoords.clear();
3413 mPointerSimple.currentProperties.clear();
3414
3415 bool down, hovering;
3416 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3417 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3418 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003419 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3420 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003421
3422 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3423 down = !hovering;
3424
Prabir Pradhand7482e72021-03-09 13:54:55 -08003425 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003426 mPointerSimple.currentCoords.copyFrom(
3427 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3428 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3429 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3430 mPointerSimple.currentProperties.id = 0;
3431 mPointerSimple.currentProperties.toolType =
3432 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3433 } else {
3434 down = false;
3435 hovering = false;
3436 }
3437
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003438 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003439}
3440
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003441void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3442 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003443}
3444
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003445void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003446 mPointerSimple.currentCoords.clear();
3447 mPointerSimple.currentProperties.clear();
3448
3449 bool down, hovering;
3450 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3451 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3452 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3453 float deltaX = 0, deltaY = 0;
3454 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3455 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3456 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3457 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3458 mPointerXMovementScale;
3459 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3460 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3461 mPointerYMovementScale;
3462
3463 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3464 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3465
Prabir Pradhand7482e72021-03-09 13:54:55 -08003466 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003467 } else {
3468 mPointerVelocityControl.reset();
3469 }
3470
3471 down = isPointerDown(mCurrentRawState.buttonState);
3472 hovering = !down;
3473
Prabir Pradhand7482e72021-03-09 13:54:55 -08003474 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003475 mPointerSimple.currentCoords.copyFrom(
3476 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3477 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3478 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3479 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3480 hovering ? 0.0f : 1.0f);
3481 mPointerSimple.currentProperties.id = 0;
3482 mPointerSimple.currentProperties.toolType =
3483 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3484 } else {
3485 mPointerVelocityControl.reset();
3486
3487 down = false;
3488 hovering = false;
3489 }
3490
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003491 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003492}
3493
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003494void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3495 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003496
3497 mPointerVelocityControl.reset();
3498}
3499
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003500void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3501 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003502 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003503
3504 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003505 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003506 mPointerController->clearSpots();
3507 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003508 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003510 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003511 }
Garfield Tan9514d782020-11-10 16:37:23 -08003512 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003513
Prabir Pradhand7482e72021-03-09 13:54:55 -08003514 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515
3516 if (mPointerSimple.down && !down) {
3517 mPointerSimple.down = false;
3518
3519 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003520 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3521 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003522 mLastRawState.buttonState, MotionClassification::NONE,
3523 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3524 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3525 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3526 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003527 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003528 }
3529
3530 if (mPointerSimple.hovering && !hovering) {
3531 mPointerSimple.hovering = false;
3532
3533 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003534 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3535 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3536 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003537 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3538 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3539 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3540 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003541 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003542 }
3543
3544 if (down) {
3545 if (!mPointerSimple.down) {
3546 mPointerSimple.down = true;
3547 mPointerSimple.downTime = when;
3548
3549 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003550 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003551 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3552 metaState, mCurrentRawState.buttonState,
3553 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3554 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3555 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3556 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003557 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003558 }
3559
3560 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003561 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3562 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003563 mCurrentRawState.buttonState, MotionClassification::NONE,
3564 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3565 &mPointerSimple.currentCoords, mOrientedXPrecision,
3566 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3567 mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003568 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003569 }
3570
3571 if (hovering) {
3572 if (!mPointerSimple.hovering) {
3573 mPointerSimple.hovering = true;
3574
3575 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003576 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003577 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3578 metaState, mCurrentRawState.buttonState,
3579 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3580 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3581 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3582 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003583 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003584 }
3585
3586 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003587 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3588 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3589 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003590 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3591 &mPointerSimple.currentCoords, mOrientedXPrecision,
3592 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3593 mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003594 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003595 }
3596
3597 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3598 float vscroll = mCurrentRawState.rawVScroll;
3599 float hscroll = mCurrentRawState.rawHScroll;
3600 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3601 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3602
3603 // Send scroll.
3604 PointerCoords pointerCoords;
3605 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3606 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3607 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3608
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003609 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3610 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003611 mCurrentRawState.buttonState, MotionClassification::NONE,
3612 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3613 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3614 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3615 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003616 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003617 }
3618
3619 // Save state.
3620 if (down || hovering) {
3621 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3622 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3623 } else {
3624 mPointerSimple.reset();
3625 }
3626}
3627
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003628void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629 mPointerSimple.currentCoords.clear();
3630 mPointerSimple.currentProperties.clear();
3631
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003632 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003633}
3634
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003635void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3636 uint32_t source, int32_t action, int32_t actionButton,
3637 int32_t flags, int32_t metaState, int32_t buttonState,
3638 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003639 const PointerCoords* coords, const uint32_t* idToIndex,
3640 BitSet32 idBits, int32_t changedId, float xPrecision,
3641 float yPrecision, nsecs_t downTime) {
3642 PointerCoords pointerCoords[MAX_POINTERS];
3643 PointerProperties pointerProperties[MAX_POINTERS];
3644 uint32_t pointerCount = 0;
3645 while (!idBits.isEmpty()) {
3646 uint32_t id = idBits.clearFirstMarkedBit();
3647 uint32_t index = idToIndex[id];
3648 pointerProperties[pointerCount].copyFrom(properties[index]);
3649 pointerCoords[pointerCount].copyFrom(coords[index]);
3650
3651 if (changedId >= 0 && id == uint32_t(changedId)) {
3652 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3653 }
3654
3655 pointerCount += 1;
3656 }
3657
3658 ALOG_ASSERT(pointerCount != 0);
3659
3660 if (changedId >= 0 && pointerCount == 1) {
3661 // Replace initial down and final up action.
3662 // We can compare the action without masking off the changed pointer index
3663 // because we know the index is 0.
3664 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3665 action = AMOTION_EVENT_ACTION_DOWN;
3666 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003667 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3668 action = AMOTION_EVENT_ACTION_CANCEL;
3669 } else {
3670 action = AMOTION_EVENT_ACTION_UP;
3671 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003672 } else {
3673 // Can't happen.
3674 ALOG_ASSERT(false);
3675 }
3676 }
3677 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3678 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003679 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003680 auto [x, y] = getMouseCursorPosition();
3681 xCursorPosition = x;
3682 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003683 }
3684 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3685 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003686 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003687 std::for_each(frames.begin(), frames.end(),
3688 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003689 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3690 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003691 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3692 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3693 downTime, std::move(frames));
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003694 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003695}
3696
3697bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3698 const PointerCoords* inCoords,
3699 const uint32_t* inIdToIndex,
3700 PointerProperties* outProperties,
3701 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3702 BitSet32 idBits) const {
3703 bool changed = false;
3704 while (!idBits.isEmpty()) {
3705 uint32_t id = idBits.clearFirstMarkedBit();
3706 uint32_t inIndex = inIdToIndex[id];
3707 uint32_t outIndex = outIdToIndex[id];
3708
3709 const PointerProperties& curInProperties = inProperties[inIndex];
3710 const PointerCoords& curInCoords = inCoords[inIndex];
3711 PointerProperties& curOutProperties = outProperties[outIndex];
3712 PointerCoords& curOutCoords = outCoords[outIndex];
3713
3714 if (curInProperties != curOutProperties) {
3715 curOutProperties.copyFrom(curInProperties);
3716 changed = true;
3717 }
3718
3719 if (curInCoords != curOutCoords) {
3720 curOutCoords.copyFrom(curInCoords);
3721 changed = true;
3722 }
3723 }
3724 return changed;
3725}
3726
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003727void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3728 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3729 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003730}
3731
Arthur Hung4197f6b2020-03-16 15:39:59 +08003732// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003733void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003734 // Scale to surface coordinate.
3735 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3736 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3737
arthurhunga36b28e2020-12-29 20:28:15 +08003738 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3739 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3740
Arthur Hung4197f6b2020-03-16 15:39:59 +08003741 // Rotate to surface coordinate.
3742 // 0 - no swap and reverse.
3743 // 90 - swap x/y and reverse y.
3744 // 180 - reverse x, y.
3745 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003746 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003747 case DISPLAY_ORIENTATION_0:
3748 x = xScaled + mXTranslate;
3749 y = yScaled + mYTranslate;
3750 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003751 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003752 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003753 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003754 break;
3755 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003756 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3757 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003758 break;
3759 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003760 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003761 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003762 break;
3763 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003764 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003765 }
3766}
3767
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003768bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003769 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3770 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3771
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003772 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003773 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003774 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003775 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003776}
3777
3778const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3779 for (const VirtualKey& virtualKey : mVirtualKeys) {
3780#if DEBUG_VIRTUAL_KEYS
3781 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3782 "left=%d, top=%d, right=%d, bottom=%d",
3783 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3784 virtualKey.hitRight, virtualKey.hitBottom);
3785#endif
3786
3787 if (virtualKey.isHit(x, y)) {
3788 return &virtualKey;
3789 }
3790 }
3791
3792 return nullptr;
3793}
3794
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003795void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3796 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3797 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003798
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003799 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003800
3801 if (currentPointerCount == 0) {
3802 // No pointers to assign.
3803 return;
3804 }
3805
3806 if (lastPointerCount == 0) {
3807 // All pointers are new.
3808 for (uint32_t i = 0; i < currentPointerCount; i++) {
3809 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003810 current.rawPointerData.pointers[i].id = id;
3811 current.rawPointerData.idToIndex[id] = i;
3812 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003813 }
3814 return;
3815 }
3816
3817 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003818 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003819 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003820 uint32_t id = last.rawPointerData.pointers[0].id;
3821 current.rawPointerData.pointers[0].id = id;
3822 current.rawPointerData.idToIndex[id] = 0;
3823 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003824 return;
3825 }
3826
3827 // General case.
3828 // We build a heap of squared euclidean distances between current and last pointers
3829 // associated with the current and last pointer indices. Then, we find the best
3830 // match (by distance) for each current pointer.
3831 // The pointers must have the same tool type but it is possible for them to
3832 // transition from hovering to touching or vice-versa while retaining the same id.
3833 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3834
3835 uint32_t heapSize = 0;
3836 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3837 currentPointerIndex++) {
3838 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3839 lastPointerIndex++) {
3840 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003841 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003842 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003843 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003844 if (currentPointer.toolType == lastPointer.toolType) {
3845 int64_t deltaX = currentPointer.x - lastPointer.x;
3846 int64_t deltaY = currentPointer.y - lastPointer.y;
3847
3848 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3849
3850 // Insert new element into the heap (sift up).
3851 heap[heapSize].currentPointerIndex = currentPointerIndex;
3852 heap[heapSize].lastPointerIndex = lastPointerIndex;
3853 heap[heapSize].distance = distance;
3854 heapSize += 1;
3855 }
3856 }
3857 }
3858
3859 // Heapify
3860 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3861 startIndex -= 1;
3862 for (uint32_t parentIndex = startIndex;;) {
3863 uint32_t childIndex = parentIndex * 2 + 1;
3864 if (childIndex >= heapSize) {
3865 break;
3866 }
3867
3868 if (childIndex + 1 < heapSize &&
3869 heap[childIndex + 1].distance < heap[childIndex].distance) {
3870 childIndex += 1;
3871 }
3872
3873 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3874 break;
3875 }
3876
3877 swap(heap[parentIndex], heap[childIndex]);
3878 parentIndex = childIndex;
3879 }
3880 }
3881
3882#if DEBUG_POINTER_ASSIGNMENT
3883 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3884 for (size_t i = 0; i < heapSize; i++) {
3885 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3886 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3887 }
3888#endif
3889
3890 // Pull matches out by increasing order of distance.
3891 // To avoid reassigning pointers that have already been matched, the loop keeps track
3892 // of which last and current pointers have been matched using the matchedXXXBits variables.
3893 // It also tracks the used pointer id bits.
3894 BitSet32 matchedLastBits(0);
3895 BitSet32 matchedCurrentBits(0);
3896 BitSet32 usedIdBits(0);
3897 bool first = true;
3898 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3899 while (heapSize > 0) {
3900 if (first) {
3901 // The first time through the loop, we just consume the root element of
3902 // the heap (the one with smallest distance).
3903 first = false;
3904 } else {
3905 // Previous iterations consumed the root element of the heap.
3906 // Pop root element off of the heap (sift down).
3907 heap[0] = heap[heapSize];
3908 for (uint32_t parentIndex = 0;;) {
3909 uint32_t childIndex = parentIndex * 2 + 1;
3910 if (childIndex >= heapSize) {
3911 break;
3912 }
3913
3914 if (childIndex + 1 < heapSize &&
3915 heap[childIndex + 1].distance < heap[childIndex].distance) {
3916 childIndex += 1;
3917 }
3918
3919 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3920 break;
3921 }
3922
3923 swap(heap[parentIndex], heap[childIndex]);
3924 parentIndex = childIndex;
3925 }
3926
3927#if DEBUG_POINTER_ASSIGNMENT
3928 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003929 for (size_t j = 0; j < heapSize; j++) {
3930 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3931 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003932 }
3933#endif
3934 }
3935
3936 heapSize -= 1;
3937
3938 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3939 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3940
3941 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3942 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3943
3944 matchedCurrentBits.markBit(currentPointerIndex);
3945 matchedLastBits.markBit(lastPointerIndex);
3946
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003947 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3948 current.rawPointerData.pointers[currentPointerIndex].id = id;
3949 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3950 current.rawPointerData.markIdBit(id,
3951 current.rawPointerData.isHovering(
3952 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003953 usedIdBits.markBit(id);
3954
3955#if DEBUG_POINTER_ASSIGNMENT
3956 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3957 ", distance=%" PRIu64,
3958 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3959#endif
3960 break;
3961 }
3962 }
3963
3964 // Assign fresh ids to pointers that were not matched in the process.
3965 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3966 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3967 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3968
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003969 current.rawPointerData.pointers[currentPointerIndex].id = id;
3970 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3971 current.rawPointerData.markIdBit(id,
3972 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003973
3974#if DEBUG_POINTER_ASSIGNMENT
3975 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3976#endif
3977 }
3978}
3979
3980int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3981 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3982 return AKEY_STATE_VIRTUAL;
3983 }
3984
3985 for (const VirtualKey& virtualKey : mVirtualKeys) {
3986 if (virtualKey.keyCode == keyCode) {
3987 return AKEY_STATE_UP;
3988 }
3989 }
3990
3991 return AKEY_STATE_UNKNOWN;
3992}
3993
3994int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3995 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3996 return AKEY_STATE_VIRTUAL;
3997 }
3998
3999 for (const VirtualKey& virtualKey : mVirtualKeys) {
4000 if (virtualKey.scanCode == scanCode) {
4001 return AKEY_STATE_UP;
4002 }
4003 }
4004
4005 return AKEY_STATE_UNKNOWN;
4006}
4007
4008bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4009 const int32_t* keyCodes, uint8_t* outFlags) {
4010 for (const VirtualKey& virtualKey : mVirtualKeys) {
4011 for (size_t i = 0; i < numCodes; i++) {
4012 if (virtualKey.keyCode == keyCodes[i]) {
4013 outFlags[i] = 1;
4014 }
4015 }
4016 }
4017
4018 return true;
4019}
4020
4021std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4022 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004023 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004024 return std::make_optional(mPointerController->getDisplayId());
4025 } else {
4026 return std::make_optional(mViewport.displayId);
4027 }
4028 }
4029 return std::nullopt;
4030}
4031
Prabir Pradhand7482e72021-03-09 13:54:55 -08004032void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004033 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4034 // space that is oriented with the viewport.
4035 rotateDelta(mViewport.orientation, &dx, &dy);
Prabir Pradhand7482e72021-03-09 13:54:55 -08004036
4037 mPointerController->move(dx, dy);
4038}
4039
4040std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4041 float x = 0;
4042 float y = 0;
4043 mPointerController->getPosition(&x, &y);
4044
Prabir Pradhand7482e72021-03-09 13:54:55 -08004045 if (!mViewport.isValid()) return {x, y};
4046
4047 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4048 // to InputReader's un-rotated coordinate space.
4049 const int32_t orientation = getInverseRotation(mViewport.orientation);
4050 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4051 return {x, y};
4052}
4053
4054void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004055 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4056 // coordinate space that is oriented with the viewport.
4057 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhand7482e72021-03-09 13:54:55 -08004058
4059 mPointerController->setPosition(x, y);
4060}
4061
4062void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4063 BitSet32 spotIdBits, int32_t displayId) {
4064 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4065
4066 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4067 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4068 float x = spotCoords[index].getX();
4069 float y = spotCoords[index].getY();
4070 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4071
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004072 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4073 // coordinate space.
4074 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhand7482e72021-03-09 13:54:55 -08004075
4076 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4077 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4078 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4079 }
4080
4081 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4082}
4083
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004084} // namespace android