blob: 046323de841261260b709d96c9e469334e3a3767 [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),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700171 mDisplayWidth(-1),
172 mDisplayHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700173 mPhysicalWidth(-1),
174 mPhysicalHeight(-1),
175 mPhysicalLeft(0),
176 mPhysicalTop(0),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700177 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700178
179TouchInputMapper::~TouchInputMapper() {}
180
181uint32_t TouchInputMapper::getSources() {
182 return mSource;
183}
184
185void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
186 InputMapper::populateDeviceInfo(info);
187
Michael Wright227c5542020-07-02 18:30:52 +0100188 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700189 info->addMotionRange(mOrientedRanges.x);
190 info->addMotionRange(mOrientedRanges.y);
191 info->addMotionRange(mOrientedRanges.pressure);
192
Chris Yef74dc422020-09-02 22:41:50 -0700193 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700194 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
195 //
196 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
197 // motion, i.e. the hardware dimensions, as the finger could move completely across the
198 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700199 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
200 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
201 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
202 x.fuzz, x.resolution);
203 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
204 y.fuzz, y.resolution);
205 }
206
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207 if (mOrientedRanges.haveSize) {
208 info->addMotionRange(mOrientedRanges.size);
209 }
210
211 if (mOrientedRanges.haveTouchSize) {
212 info->addMotionRange(mOrientedRanges.touchMajor);
213 info->addMotionRange(mOrientedRanges.touchMinor);
214 }
215
216 if (mOrientedRanges.haveToolSize) {
217 info->addMotionRange(mOrientedRanges.toolMajor);
218 info->addMotionRange(mOrientedRanges.toolMinor);
219 }
220
221 if (mOrientedRanges.haveOrientation) {
222 info->addMotionRange(mOrientedRanges.orientation);
223 }
224
225 if (mOrientedRanges.haveDistance) {
226 info->addMotionRange(mOrientedRanges.distance);
227 }
228
229 if (mOrientedRanges.haveTilt) {
230 info->addMotionRange(mOrientedRanges.tilt);
231 }
232
233 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
234 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
235 0.0f);
236 }
237 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
238 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
239 0.0f);
240 }
Michael Wright227c5542020-07-02 18:30:52 +0100241 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700242 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
243 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
244 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
245 x.fuzz, x.resolution);
246 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
247 y.fuzz, y.resolution);
248 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
249 x.fuzz, x.resolution);
250 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
251 y.fuzz, y.resolution);
252 }
253 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
254 }
255}
256
257void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700258 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800259 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700260 dumpParameters(dump);
261 dumpVirtualKeys(dump);
262 dumpRawPointerAxes(dump);
263 dumpCalibration(dump);
264 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700265 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700266
267 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700268 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
269 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
270 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
271 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
272 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
273 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
274 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
275 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
276 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
277 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
278 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
279 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
280 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
281 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
282
283 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
284 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
285 mLastRawState.rawPointerData.pointerCount);
286 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
287 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
288 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
289 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
290 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
291 "toolType=%d, isHovering=%s\n",
292 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
293 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
294 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
295 pointer.distance, pointer.toolType, toString(pointer.isHovering));
296 }
297
298 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
299 mLastCookedState.buttonState);
300 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
301 mLastCookedState.cookedPointerData.pointerCount);
302 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
303 const PointerProperties& pointerProperties =
304 mLastCookedState.cookedPointerData.pointerProperties[i];
305 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000306 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
307 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
308 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700309 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
310 "toolType=%d, isHovering=%s\n",
311 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000312 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
313 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
315 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
316 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
322 pointerProperties.toolType,
323 toString(mLastCookedState.cookedPointerData.isHovering(i)));
324 }
325
326 dump += INDENT3 "Stylus Fusion:\n";
327 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
328 toString(mExternalStylusConnected));
329 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
330 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
331 mExternalStylusFusionTimeout);
332 dump += INDENT3 "External Stylus State:\n";
333 dumpStylusState(dump, mExternalStylusState);
334
Michael Wright227c5542020-07-02 18:30:52 +0100335 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700336 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
337 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
338 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
339 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
340 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
341 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
342 }
343}
344
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
346 uint32_t changes) {
347 InputMapper::configure(when, config, changes);
348
349 mConfig = *config;
350
351 if (!changes) { // first time only
352 // Configure basic parameters.
353 configureParameters();
354
355 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800356 mCursorScrollAccumulator.configure(getDeviceContext());
357 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700358
359 // Configure absolute axis information.
360 configureRawPointerAxes();
361
362 // Prepare input device calibration.
363 parseCalibration();
364 resolveCalibration();
365 }
366
367 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
368 // Update location calibration to reflect current settings
369 updateAffineTransformation();
370 }
371
372 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
373 // Update pointer speed.
374 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
375 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
376 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
377 }
378
379 bool resetNeeded = false;
380 if (!changes ||
381 (changes &
382 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800383 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
385 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
386 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700387 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700388 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700389 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390 }
391
392 if (changes && resetNeeded) {
393 // Send reset, unless this is the first time the device has been configured,
394 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +0000395 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700396 getListener().notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700397 }
398}
399
400void TouchInputMapper::resolveExternalStylusPresence() {
401 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800402 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700403 mExternalStylusConnected = !devices.empty();
404
405 if (!mExternalStylusConnected) {
406 resetExternalStylus();
407 }
408}
409
410void TouchInputMapper::configureParameters() {
411 // Use the pointer presentation mode for devices that do not support distinct
412 // multitouch. The spot-based presentation relies on being able to accurately
413 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800414 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100415 ? Parameters::GestureMode::SINGLE_TOUCH
416 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700417
418 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
420 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100422 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100424 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700425 } else if (gestureModeString != "default") {
426 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
427 }
428 }
429
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800430 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700431 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100432 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800433 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700434 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100435 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800436 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
437 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438 // The device is a cursor device with a touch pad attached.
439 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700441 } else {
442 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100443 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444 }
445
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800446 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447
448 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800449 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
450 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700451 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100452 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700453 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100454 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100456 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100458 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 } else if (deviceTypeString != "default") {
460 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
461 }
462 }
463
Michael Wright227c5542020-07-02 18:30:52 +0100464 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800465 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
466 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700467
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700468 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
469 String8 orientationString;
470 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientation"),
471 orientationString)) {
472 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
473 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
474 } else if (orientationString == "ORIENTATION_90") {
475 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
476 } else if (orientationString == "ORIENTATION_180") {
477 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
478 } else if (orientationString == "ORIENTATION_270") {
479 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
480 } else if (orientationString != "ORIENTATION_0") {
481 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.string());
482 }
483 }
484
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700485 mParameters.hasAssociatedDisplay = false;
486 mParameters.associatedDisplayIsExternal = false;
487 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100488 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
489 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700490 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100491 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800492 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700493 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
495 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
497 }
498 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800499 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700500 mParameters.hasAssociatedDisplay = true;
501 }
502
503 // Initial downs on external touch devices should wake the device.
504 // Normally we don't do this for internal touch screens to prevent them from waking
505 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800506 mParameters.wake = getDeviceContext().isExternal();
507 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700508}
509
510void TouchInputMapper::dumpParameters(std::string& dump) {
511 dump += INDENT3 "Parameters:\n";
512
Dominik Laskowski75788452021-02-09 18:51:25 -0800513 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514
Dominik Laskowski75788452021-02-09 18:51:25 -0800515 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700516
517 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
518 "displayId='%s'\n",
519 toString(mParameters.hasAssociatedDisplay),
520 toString(mParameters.associatedDisplayIsExternal),
521 mParameters.uniqueDisplayId.c_str());
522 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800523 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700524}
525
526void TouchInputMapper::configureRawPointerAxes() {
527 mRawPointerAxes.clear();
528}
529
530void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
531 dump += INDENT3 "Raw Touch Axes:\n";
532 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
533 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
534 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
535 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
536 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
537 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
538 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
545}
546
547bool TouchInputMapper::hasExternalStylus() const {
548 return mExternalStylusConnected;
549}
550
551/**
552 * Determine which DisplayViewport to use.
553 * 1. If display port is specified, return the matching viewport. If matching viewport not
554 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800555 * 2. Always use the suggested viewport from WindowManagerService for pointers.
556 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700557 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800558 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700559 */
560std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800561 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800562 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700563 if (displayPort) {
564 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800565 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 }
567
Michael Wright227c5542020-07-02 18:30:52 +0100568 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800569 std::optional<DisplayViewport> viewport =
570 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
571 if (viewport) {
572 return viewport;
573 } else {
574 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
575 mConfig.defaultPointerDisplayId);
576 }
577 }
578
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700579 // Check if uniqueDisplayId is specified in idc file.
580 if (!mParameters.uniqueDisplayId.empty()) {
581 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
582 }
583
584 ViewportType viewportTypeToUse;
585 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100586 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700587 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100588 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700589 }
590
591 std::optional<DisplayViewport> viewport =
592 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100593 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700594 ALOGW("Input device %s should be associated with external display, "
595 "fallback to internal one for the external viewport is not found.",
596 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100597 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700598 }
599
600 return viewport;
601 }
602
603 // No associated display, return a non-display viewport.
604 DisplayViewport newViewport;
605 // Raw width and height in the natural orientation.
606 int32_t rawWidth = mRawPointerAxes.getRawWidth();
607 int32_t rawHeight = mRawPointerAxes.getRawHeight();
608 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
609 return std::make_optional(newViewport);
610}
611
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800612void TouchInputMapper::initializeSizeRanges() {
613 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
614 mSizeScale = 0.0f;
615 return;
616 }
617
618 // Size of diagonal axis.
619 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
620
621 // Size factors.
622 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
623 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
624 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
625 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
626 } else {
627 mSizeScale = 0.0f;
628 }
629
630 mOrientedRanges.haveTouchSize = true;
631 mOrientedRanges.haveToolSize = true;
632 mOrientedRanges.haveSize = true;
633
634 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
635 mOrientedRanges.touchMajor.source = mSource;
636 mOrientedRanges.touchMajor.min = 0;
637 mOrientedRanges.touchMajor.max = diagonalSize;
638 mOrientedRanges.touchMajor.flat = 0;
639 mOrientedRanges.touchMajor.fuzz = 0;
640 mOrientedRanges.touchMajor.resolution = 0;
641
642 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
643 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
644
645 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
646 mOrientedRanges.toolMajor.source = mSource;
647 mOrientedRanges.toolMajor.min = 0;
648 mOrientedRanges.toolMajor.max = diagonalSize;
649 mOrientedRanges.toolMajor.flat = 0;
650 mOrientedRanges.toolMajor.fuzz = 0;
651 mOrientedRanges.toolMajor.resolution = 0;
652
653 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
654 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
655
656 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
657 mOrientedRanges.size.source = mSource;
658 mOrientedRanges.size.min = 0;
659 mOrientedRanges.size.max = 1.0;
660 mOrientedRanges.size.flat = 0;
661 mOrientedRanges.size.fuzz = 0;
662 mOrientedRanges.size.resolution = 0;
663}
664
665void TouchInputMapper::initializeOrientedRanges() {
666 // Configure X and Y factors.
667 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
668 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
669 mXPrecision = 1.0f / mXScale;
670 mYPrecision = 1.0f / mYScale;
671
672 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
673 mOrientedRanges.x.source = mSource;
674 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
675 mOrientedRanges.y.source = mSource;
676
677 // Scale factor for terms that are not oriented in a particular axis.
678 // If the pixels are square then xScale == yScale otherwise we fake it
679 // by choosing an average.
680 mGeometricScale = avg(mXScale, mYScale);
681
682 initializeSizeRanges();
683
684 // Pressure factors.
685 mPressureScale = 0;
686 float pressureMax = 1.0;
687 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
688 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
689 if (mCalibration.havePressureScale) {
690 mPressureScale = mCalibration.pressureScale;
691 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
692 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
693 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
694 }
695 }
696
697 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
698 mOrientedRanges.pressure.source = mSource;
699 mOrientedRanges.pressure.min = 0;
700 mOrientedRanges.pressure.max = pressureMax;
701 mOrientedRanges.pressure.flat = 0;
702 mOrientedRanges.pressure.fuzz = 0;
703 mOrientedRanges.pressure.resolution = 0;
704
705 // Tilt
706 mTiltXCenter = 0;
707 mTiltXScale = 0;
708 mTiltYCenter = 0;
709 mTiltYScale = 0;
710 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
711 if (mHaveTilt) {
712 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
713 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
714 mTiltXScale = M_PI / 180;
715 mTiltYScale = M_PI / 180;
716
717 if (mRawPointerAxes.tiltX.resolution) {
718 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
719 }
720 if (mRawPointerAxes.tiltY.resolution) {
721 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
722 }
723
724 mOrientedRanges.haveTilt = true;
725
726 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
727 mOrientedRanges.tilt.source = mSource;
728 mOrientedRanges.tilt.min = 0;
729 mOrientedRanges.tilt.max = M_PI_2;
730 mOrientedRanges.tilt.flat = 0;
731 mOrientedRanges.tilt.fuzz = 0;
732 mOrientedRanges.tilt.resolution = 0;
733 }
734
735 // Orientation
736 mOrientationScale = 0;
737 if (mHaveTilt) {
738 mOrientedRanges.haveOrientation = true;
739
740 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
741 mOrientedRanges.orientation.source = mSource;
742 mOrientedRanges.orientation.min = -M_PI;
743 mOrientedRanges.orientation.max = M_PI;
744 mOrientedRanges.orientation.flat = 0;
745 mOrientedRanges.orientation.fuzz = 0;
746 mOrientedRanges.orientation.resolution = 0;
747 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
748 if (mCalibration.orientationCalibration ==
749 Calibration::OrientationCalibration::INTERPOLATED) {
750 if (mRawPointerAxes.orientation.valid) {
751 if (mRawPointerAxes.orientation.maxValue > 0) {
752 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
753 } else if (mRawPointerAxes.orientation.minValue < 0) {
754 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
755 } else {
756 mOrientationScale = 0;
757 }
758 }
759 }
760
761 mOrientedRanges.haveOrientation = true;
762
763 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
764 mOrientedRanges.orientation.source = mSource;
765 mOrientedRanges.orientation.min = -M_PI_2;
766 mOrientedRanges.orientation.max = M_PI_2;
767 mOrientedRanges.orientation.flat = 0;
768 mOrientedRanges.orientation.fuzz = 0;
769 mOrientedRanges.orientation.resolution = 0;
770 }
771
772 // Distance
773 mDistanceScale = 0;
774 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
775 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
776 if (mCalibration.haveDistanceScale) {
777 mDistanceScale = mCalibration.distanceScale;
778 } else {
779 mDistanceScale = 1.0f;
780 }
781 }
782
783 mOrientedRanges.haveDistance = true;
784
785 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
786 mOrientedRanges.distance.source = mSource;
787 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
788 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
789 mOrientedRanges.distance.flat = 0;
790 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
791 mOrientedRanges.distance.resolution = 0;
792 }
793
794 // Compute oriented precision, scales and ranges.
795 // Note that the maximum value reported is an inclusive maximum value so it is one
796 // unit less than the total width or height of the display.
797 switch (mInputDeviceOrientation) {
798 case DISPLAY_ORIENTATION_90:
799 case DISPLAY_ORIENTATION_270:
800 mOrientedXPrecision = mYPrecision;
801 mOrientedYPrecision = mXPrecision;
802
803 mOrientedRanges.x.min = 0;
804 mOrientedRanges.x.max = mDisplayHeight - 1;
805 mOrientedRanges.x.flat = 0;
806 mOrientedRanges.x.fuzz = 0;
807 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
808
809 mOrientedRanges.y.min = 0;
810 mOrientedRanges.y.max = mDisplayWidth - 1;
811 mOrientedRanges.y.flat = 0;
812 mOrientedRanges.y.fuzz = 0;
813 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
814 break;
815
816 default:
817 mOrientedXPrecision = mXPrecision;
818 mOrientedYPrecision = mYPrecision;
819
820 mOrientedRanges.x.min = 0;
821 mOrientedRanges.x.max = mDisplayWidth - 1;
822 mOrientedRanges.x.flat = 0;
823 mOrientedRanges.x.fuzz = 0;
824 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
825
826 mOrientedRanges.y.min = 0;
827 mOrientedRanges.y.max = mDisplayHeight - 1;
828 mOrientedRanges.y.flat = 0;
829 mOrientedRanges.y.fuzz = 0;
830 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
831 break;
832 }
833}
834
Prabir Pradhan1728b212021-10-19 16:00:03 -0700835void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100836 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700837
838 resolveExternalStylusPresence();
839
840 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100841 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000842 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700843 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100844 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700845 if (hasStylus()) {
846 mSource |= AINPUT_SOURCE_STYLUS;
847 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800848 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700849 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100850 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700851 if (hasStylus()) {
852 mSource |= AINPUT_SOURCE_STYLUS;
853 }
854 if (hasExternalStylus()) {
855 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
856 }
Michael Wright227c5542020-07-02 18:30:52 +0100857 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700858 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100859 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700860 } else {
861 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100862 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700863 }
864
865 // Ensure we have valid X and Y axes.
866 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
867 ALOGW("Touch device '%s' did not report support for X or Y axis! "
868 "The device will be inoperable.",
869 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100870 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700871 return;
872 }
873
874 // Get associated display dimensions.
875 std::optional<DisplayViewport> newViewport = findViewport();
876 if (!newViewport) {
877 ALOGI("Touch device '%s' could not query the properties of its associated "
878 "display. The device will be inoperable until the display size "
879 "becomes available.",
880 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100881 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700882 return;
883 }
884
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000885 if (!newViewport->isActive) {
886 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
887 getDeviceName().c_str(), getDeviceId());
888 mDeviceMode = DeviceMode::DISABLED;
889 return;
890 }
891
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700892 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700893 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
894 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700895
Prabir Pradhan1728b212021-10-19 16:00:03 -0700896 const bool viewportChanged = mViewport != *newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700897 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700898 if (viewportChanged) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700899 const bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700900 mViewport = *newViewport;
901
Michael Wright227c5542020-07-02 18:30:52 +0100902 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700903 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
905 int32_t naturalPhysicalLeft, naturalPhysicalTop;
906 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700907
Prabir Pradhan1728b212021-10-19 16:00:03 -0700908 // Apply the inverse of the input device orientation so that the input device is
909 // configured in the same orientation as the viewport. The input device orientation will
910 // be re-applied by mInputDeviceOrientation.
911 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700912 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700913 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700914 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700915 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
916 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800917 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700918 naturalPhysicalTop = mViewport.physicalLeft;
919 naturalDeviceWidth = mViewport.deviceHeight;
920 naturalDeviceHeight = mViewport.deviceWidth;
921 break;
922 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700923 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
924 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
925 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
926 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
927 naturalDeviceWidth = mViewport.deviceWidth;
928 naturalDeviceHeight = mViewport.deviceHeight;
929 break;
930 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
932 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
933 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800934 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700935 naturalDeviceWidth = mViewport.deviceHeight;
936 naturalDeviceHeight = mViewport.deviceWidth;
937 break;
938 case DISPLAY_ORIENTATION_0:
939 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700940 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
941 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
942 naturalPhysicalLeft = mViewport.physicalLeft;
943 naturalPhysicalTop = mViewport.physicalTop;
944 naturalDeviceWidth = mViewport.deviceWidth;
945 naturalDeviceHeight = mViewport.deviceHeight;
946 break;
947 }
948
949 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
950 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
951 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
952 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
953 }
954
955 mPhysicalWidth = naturalPhysicalWidth;
956 mPhysicalHeight = naturalPhysicalHeight;
957 mPhysicalLeft = naturalPhysicalLeft;
958 mPhysicalTop = naturalPhysicalTop;
959
Prabir Pradhan1728b212021-10-19 16:00:03 -0700960 const int32_t oldDisplayWidth = mDisplayWidth;
961 const int32_t oldDisplayHeight = mDisplayHeight;
962 mDisplayWidth = naturalDeviceWidth;
963 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700964
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000965 // InputReader works in the un-rotated display coordinate space, so we don't need to do
966 // anything if the device is already orientation-aware. If the device is not
967 // orientation-aware, then we need to apply the inverse rotation of the display so that
968 // when the display rotation is applied later as a part of the per-window transform, we
969 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700970 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000971 ? DISPLAY_ORIENTATION_0
972 : getInverseRotation(mViewport.orientation);
973 // For orientation-aware devices that work in the un-rotated coordinate space, the
974 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700975 skipViewportUpdate = mParameters.orientationAware && mDisplayWidth == oldDisplayWidth &&
976 mDisplayHeight == oldDisplayHeight && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700977
978 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700979 mInputDeviceOrientation =
980 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700981 } else {
982 mPhysicalWidth = rawWidth;
983 mPhysicalHeight = rawHeight;
984 mPhysicalLeft = 0;
985 mPhysicalTop = 0;
986
Prabir Pradhan1728b212021-10-19 16:00:03 -0700987 mDisplayWidth = rawWidth;
988 mDisplayHeight = rawHeight;
989 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990 }
991 }
992
993 // If moving between pointer modes, need to reset some state.
994 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
995 if (deviceModeChanged) {
996 mOrientedRanges.clear();
997 }
998
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800999 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
1000 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +01001001 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001002 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001003 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1004 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001005 if (mPointerController == nullptr) {
1006 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001007 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001008 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001009 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1010 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011 } else {
Michael Wright17db18e2020-06-26 20:51:44 +01001012 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001013 }
1014
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001015 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001016 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1017 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001018 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1019 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001020
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001021 configureVirtualKeys();
1022
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001023 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001024
1025 // Location
1026 updateAffineTransformation();
1027
Michael Wright227c5542020-07-02 18:30:52 +01001028 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001029 // Compute pointer gesture detection parameters.
1030 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001031 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032
1033 // Scale movements such that one whole swipe of the touch pad covers a
1034 // given area relative to the diagonal size of the display when no acceleration
1035 // is applied.
1036 // Assume that the touch pad has a square aspect ratio such that movements in
1037 // X and Y of the same number of raw units cover the same physical distance.
1038 mPointerXMovementScale =
1039 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1040 mPointerYMovementScale = mPointerXMovementScale;
1041
1042 // Scale zooms to cover a smaller range of the display than movements do.
1043 // This value determines the area around the pointer that is affected by freeform
1044 // pointer gestures.
1045 mPointerXZoomScale =
1046 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1047 mPointerYZoomScale = mPointerXZoomScale;
1048
1049 // Max width between pointers to detect a swipe gesture is more than some fraction
1050 // of the diagonal axis of the touch pad. Touches that are wider than this are
1051 // translated into freeform gestures.
1052 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1053
1054 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001055 const nsecs_t readTime = when; // synthetic event
1056 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057 }
1058
1059 // Inform the dispatcher about the changes.
1060 *outResetNeeded = true;
1061 bumpGeneration();
1062 }
1063}
1064
Prabir Pradhan1728b212021-10-19 16:00:03 -07001065void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001067 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1068 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001069 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1070 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1071 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1072 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001073 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001074}
1075
1076void TouchInputMapper::configureVirtualKeys() {
1077 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001078 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001079
1080 mVirtualKeys.clear();
1081
1082 if (virtualKeyDefinitions.size() == 0) {
1083 return;
1084 }
1085
1086 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1087 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1088 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1089 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1090
1091 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1092 VirtualKey virtualKey;
1093
1094 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1095 int32_t keyCode;
1096 int32_t dummyKeyMetaState;
1097 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001098 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1099 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001100 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1101 continue; // drop the key
1102 }
1103
1104 virtualKey.keyCode = keyCode;
1105 virtualKey.flags = flags;
1106
1107 // convert the key definition's display coordinates into touch coordinates for a hit box
1108 int32_t halfWidth = virtualKeyDefinition.width / 2;
1109 int32_t halfHeight = virtualKeyDefinition.height / 2;
1110
1111 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001112 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 touchScreenLeft;
1114 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001115 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001117 virtualKey.hitTop =
1118 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001119 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001120 virtualKey.hitBottom =
1121 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001122 touchScreenTop;
1123 mVirtualKeys.push_back(virtualKey);
1124 }
1125}
1126
1127void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1128 if (!mVirtualKeys.empty()) {
1129 dump += INDENT3 "Virtual Keys:\n";
1130
1131 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1132 const VirtualKey& virtualKey = mVirtualKeys[i];
1133 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1134 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1135 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1136 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1137 }
1138 }
1139}
1140
1141void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001142 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 Calibration& out = mCalibration;
1144
1145 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 String8 sizeCalibrationString;
1148 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1149 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001150 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001152 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001153 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001154 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001156 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001157 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001158 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 } else if (sizeCalibrationString != "default") {
1160 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1161 }
1162 }
1163
1164 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1165 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1166 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1167
1168 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 String8 pressureCalibrationString;
1171 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1172 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 } else if (pressureCalibrationString != "default") {
1179 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1180 pressureCalibrationString.string());
1181 }
1182 }
1183
1184 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1185
1186 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 String8 orientationCalibrationString;
1189 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1190 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001193 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001194 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 } else if (orientationCalibrationString != "default") {
1197 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1198 orientationCalibrationString.string());
1199 }
1200 }
1201
1202 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001203 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 String8 distanceCalibrationString;
1205 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1206 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 } else if (distanceCalibrationString != "default") {
1211 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1212 distanceCalibrationString.string());
1213 }
1214 }
1215
1216 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1217
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 String8 coverageCalibrationString;
1220 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1221 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 } else if (coverageCalibrationString != "default") {
1226 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1227 coverageCalibrationString.string());
1228 }
1229 }
1230}
1231
1232void TouchInputMapper::resolveCalibration() {
1233 // Size
1234 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001235 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1236 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001239 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 }
1241
1242 // Pressure
1243 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001244 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1245 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001248 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250
1251 // Orientation
1252 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001253 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1254 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001257 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
1259
1260 // Distance
1261 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001262 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1263 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001266 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 }
1268
1269 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001270 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1271 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 }
1273}
1274
1275void TouchInputMapper::dumpCalibration(std::string& dump) {
1276 dump += INDENT3 "Calibration:\n";
1277
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001278 dump += INDENT4 "touch.size.calibration: ";
1279 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280
1281 if (mCalibration.haveSizeScale) {
1282 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1283 }
1284
1285 if (mCalibration.haveSizeBias) {
1286 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1287 }
1288
1289 if (mCalibration.haveSizeIsSummed) {
1290 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1291 toString(mCalibration.sizeIsSummed));
1292 }
1293
1294 // Pressure
1295 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001296 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 dump += INDENT4 "touch.pressure.calibration: none\n";
1298 break;
Michael Wright227c5542020-07-02 18:30:52 +01001299 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 dump += INDENT4 "touch.pressure.calibration: physical\n";
1301 break;
Michael Wright227c5542020-07-02 18:30:52 +01001302 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1304 break;
1305 default:
1306 ALOG_ASSERT(false);
1307 }
1308
1309 if (mCalibration.havePressureScale) {
1310 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1311 }
1312
1313 // Orientation
1314 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.orientation.calibration: none\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1320 break;
Michael Wright227c5542020-07-02 18:30:52 +01001321 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += INDENT4 "touch.orientation.calibration: vector\n";
1323 break;
1324 default:
1325 ALOG_ASSERT(false);
1326 }
1327
1328 // Distance
1329 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.distance.calibration: none\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.distance.calibration: scaled\n";
1335 break;
1336 default:
1337 ALOG_ASSERT(false);
1338 }
1339
1340 if (mCalibration.haveDistanceScale) {
1341 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1342 }
1343
1344 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001345 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 dump += INDENT4 "touch.coverage.calibration: none\n";
1347 break;
Michael Wright227c5542020-07-02 18:30:52 +01001348 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349 dump += INDENT4 "touch.coverage.calibration: box\n";
1350 break;
1351 default:
1352 ALOG_ASSERT(false);
1353 }
1354}
1355
1356void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1357 dump += INDENT3 "Affine Transformation:\n";
1358
1359 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1360 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1361 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1362 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1363 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1364 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1365}
1366
1367void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001368 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001369 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001370}
1371
1372void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001373 mCursorButtonAccumulator.reset(getDeviceContext());
1374 mCursorScrollAccumulator.reset(getDeviceContext());
1375 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001376
1377 mPointerVelocityControl.reset();
1378 mWheelXVelocityControl.reset();
1379 mWheelYVelocityControl.reset();
1380
1381 mRawStatesPending.clear();
1382 mCurrentRawState.clear();
1383 mCurrentCookedState.clear();
1384 mLastRawState.clear();
1385 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001386 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001387 mSentHoverEnter = false;
1388 mHavePointerIds = false;
1389 mCurrentMotionAborted = false;
1390 mDownTime = 0;
1391
1392 mCurrentVirtualKey.down = false;
1393
1394 mPointerGesture.reset();
1395 mPointerSimple.reset();
1396 resetExternalStylus();
1397
1398 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001399 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001400 mPointerController->clearSpots();
1401 }
1402
1403 InputMapper::reset(when);
1404}
1405
1406void TouchInputMapper::resetExternalStylus() {
1407 mExternalStylusState.clear();
1408 mExternalStylusId = -1;
1409 mExternalStylusFusionTimeout = LLONG_MAX;
1410 mExternalStylusDataPending = false;
1411}
1412
1413void TouchInputMapper::clearStylusDataPendingFlags() {
1414 mExternalStylusDataPending = false;
1415 mExternalStylusFusionTimeout = LLONG_MAX;
1416}
1417
1418void TouchInputMapper::process(const RawEvent* rawEvent) {
1419 mCursorButtonAccumulator.process(rawEvent);
1420 mCursorScrollAccumulator.process(rawEvent);
1421 mTouchButtonAccumulator.process(rawEvent);
1422
1423 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001424 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001425 }
1426}
1427
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001428void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001429 // Push a new state.
1430 mRawStatesPending.emplace_back();
1431
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001432 RawState& next = mRawStatesPending.back();
1433 next.clear();
1434 next.when = when;
1435 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436
1437 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001438 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1440
1441 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001442 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1443 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 mCursorScrollAccumulator.finishSync();
1445
1446 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001447 syncTouch(when, &next);
1448
1449 // The last RawState is the actually second to last, since we just added a new state
1450 const RawState& last =
1451 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001452
1453 // Assign pointer ids.
1454 if (!mHavePointerIds) {
1455 assignPointerIds(last, next);
1456 }
1457
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08001458 if (DEBUG_RAW_EVENTS) {
1459 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1460 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1461 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1462 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1463 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1464 next.rawPointerData.canceledIdBits.value);
1465 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001466
Arthur Hung9ad18942021-06-19 02:04:46 +00001467 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1468 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1469 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1470 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1471 next.rawPointerData.hoveringIdBits.value);
1472 }
1473
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001474 processRawTouches(false /*timeout*/);
1475}
1476
1477void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001478 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001480 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001481 mCurrentCookedState.clear();
1482 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001483 return;
1484 }
1485
1486 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1487 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1488 // touching the current state will only observe the events that have been dispatched to the
1489 // rest of the pipeline.
1490 const size_t N = mRawStatesPending.size();
1491 size_t count;
1492 for (count = 0; count < N; count++) {
1493 const RawState& next = mRawStatesPending[count];
1494
1495 // A failure to assign the stylus id means that we're waiting on stylus data
1496 // and so should defer the rest of the pipeline.
1497 if (assignExternalStylusId(next, timeout)) {
1498 break;
1499 }
1500
1501 // All ready to go.
1502 clearStylusDataPendingFlags();
1503 mCurrentRawState.copyFrom(next);
1504 if (mCurrentRawState.when < mLastRawState.when) {
1505 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001506 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001507 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001508 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001509 }
1510 if (count != 0) {
1511 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1512 }
1513
1514 if (mExternalStylusDataPending) {
1515 if (timeout) {
1516 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1517 clearStylusDataPendingFlags();
1518 mCurrentRawState.copyFrom(mLastRawState);
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08001519 if (DEBUG_STYLUS_FUSION) {
1520 ALOGD("Timeout expired, synthesizing event with new stylus data");
1521 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001522 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1523 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1525 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1526 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1527 }
1528 }
1529}
1530
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001531void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001532 // Always start with a clean state.
1533 mCurrentCookedState.clear();
1534
1535 // Apply stylus buttons to current raw state.
1536 applyExternalStylusButtonState(when);
1537
1538 // Handle policy on initial down or hover events.
1539 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1540 mCurrentRawState.rawPointerData.pointerCount != 0;
1541
1542 uint32_t policyFlags = 0;
1543 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1544 if (initialDown || buttonsPressed) {
1545 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001546 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001547 getContext()->fadePointer();
1548 }
1549
1550 if (mParameters.wake) {
1551 policyFlags |= POLICY_FLAG_WAKE;
1552 }
1553 }
1554
1555 // Consume raw off-screen touches before cooking pointer data.
1556 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001557 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001558 mCurrentRawState.rawPointerData.clear();
1559 }
1560
1561 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1562 // with cooked pointer data that has the same ids and indices as the raw data.
1563 // The following code can use either the raw or cooked data, as needed.
1564 cookPointerData();
1565
1566 // Apply stylus pressure to current cooked state.
1567 applyExternalStylusTouchState(when);
1568
1569 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001570 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1571 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001572 mCurrentCookedState.buttonState);
1573
1574 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001575 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1577 uint32_t id = idBits.clearFirstMarkedBit();
1578 const RawPointerData::Pointer& pointer =
1579 mCurrentRawState.rawPointerData.pointerForId(id);
1580 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1581 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1582 mCurrentCookedState.stylusIdBits.markBit(id);
1583 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1584 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1585 mCurrentCookedState.fingerIdBits.markBit(id);
1586 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1587 mCurrentCookedState.mouseIdBits.markBit(id);
1588 }
1589 }
1590 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1591 uint32_t id = idBits.clearFirstMarkedBit();
1592 const RawPointerData::Pointer& pointer =
1593 mCurrentRawState.rawPointerData.pointerForId(id);
1594 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1595 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1596 mCurrentCookedState.stylusIdBits.markBit(id);
1597 }
1598 }
1599
1600 // Stylus takes precedence over all tools, then mouse, then finger.
1601 PointerUsage pointerUsage = mPointerUsage;
1602 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1603 mCurrentCookedState.mouseIdBits.clear();
1604 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001605 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1607 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001608 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001609 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1610 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001611 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001612 }
1613
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001614 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001616 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617
1618 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001619 dispatchButtonRelease(when, readTime, policyFlags);
1620 dispatchHoverExit(when, readTime, policyFlags);
1621 dispatchTouches(when, readTime, policyFlags);
1622 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1623 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 }
1625
1626 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1627 mCurrentMotionAborted = false;
1628 }
1629 }
1630
1631 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001632 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001633 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1634 mCurrentCookedState.buttonState);
1635
1636 // Clear some transient state.
1637 mCurrentRawState.rawVScroll = 0;
1638 mCurrentRawState.rawHScroll = 0;
1639
1640 // Copy current touch to last touch in preparation for the next cycle.
1641 mLastRawState.copyFrom(mCurrentRawState);
1642 mLastCookedState.copyFrom(mCurrentCookedState);
1643}
1644
Garfield Tanc734e4f2021-01-15 20:01:39 -08001645void TouchInputMapper::updateTouchSpots() {
1646 if (!mConfig.showTouches || mPointerController == nullptr) {
1647 return;
1648 }
1649
1650 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1651 // clear touch spots.
1652 if (mDeviceMode != DeviceMode::DIRECT &&
1653 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1654 return;
1655 }
1656
1657 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1658 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1659
1660 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001661 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1662 mCurrentCookedState.cookedPointerData.idToIndex,
1663 mCurrentCookedState.cookedPointerData.touchingIdBits,
1664 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001665}
1666
1667bool TouchInputMapper::isTouchScreen() {
1668 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1669 mParameters.hasAssociatedDisplay;
1670}
1671
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001672void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001673 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001674 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1675 }
1676}
1677
1678void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1679 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1680 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1681
1682 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1683 float pressure = mExternalStylusState.pressure;
1684 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1685 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1686 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1687 }
1688 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1689 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1690
1691 PointerProperties& properties =
1692 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1693 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1694 properties.toolType = mExternalStylusState.toolType;
1695 }
1696 }
1697}
1698
1699bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001700 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001701 return false;
1702 }
1703
1704 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1705 state.rawPointerData.pointerCount != 0;
1706 if (initialDown) {
1707 if (mExternalStylusState.pressure != 0.0f) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08001708 if (DEBUG_STYLUS_FUSION) {
1709 ALOGD("Have both stylus and touch data, beginning fusion");
1710 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001711 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1712 } else if (timeout) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08001713 if (DEBUG_STYLUS_FUSION) {
1714 ALOGD("Timeout expired, assuming touch is not a stylus.");
1715 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001716 resetExternalStylus();
1717 } else {
1718 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1719 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1720 }
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08001721 if (DEBUG_STYLUS_FUSION) {
1722 ALOGD("No stylus data but stylus is connected, requesting timeout "
1723 "(%" PRId64 "ms)",
1724 mExternalStylusFusionTimeout);
1725 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001726 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1727 return true;
1728 }
1729 }
1730
1731 // Check if the stylus pointer has gone up.
1732 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08001733 if (DEBUG_STYLUS_FUSION) {
1734 ALOGD("Stylus pointer is going up");
1735 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001736 mExternalStylusId = -1;
1737 }
1738
1739 return false;
1740}
1741
1742void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001743 if (mDeviceMode == DeviceMode::POINTER) {
1744 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001745 // Since this is a synthetic event, we can consider its latency to be zero
1746 const nsecs_t readTime = when;
1747 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001748 }
Michael Wright227c5542020-07-02 18:30:52 +01001749 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001750 if (mExternalStylusFusionTimeout < when) {
1751 processRawTouches(true /*timeout*/);
1752 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1753 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1754 }
1755 }
1756}
1757
1758void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1759 mExternalStylusState.copyFrom(state);
1760 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1761 // We're either in the middle of a fused stream of data or we're waiting on data before
1762 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1763 // data.
1764 mExternalStylusDataPending = true;
1765 processRawTouches(false /*timeout*/);
1766 }
1767}
1768
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001769bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001770 // Check for release of a virtual key.
1771 if (mCurrentVirtualKey.down) {
1772 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1773 // Pointer went up while virtual key was down.
1774 mCurrentVirtualKey.down = false;
1775 if (!mCurrentVirtualKey.ignored) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08001776 if (DEBUG_VIRTUAL_KEYS) {
1777 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1778 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1779 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001780 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001781 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1782 }
1783 return true;
1784 }
1785
1786 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1787 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1788 const RawPointerData::Pointer& pointer =
1789 mCurrentRawState.rawPointerData.pointerForId(id);
1790 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1791 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1792 // Pointer is still within the space of the virtual key.
1793 return true;
1794 }
1795 }
1796
1797 // Pointer left virtual key area or another pointer also went down.
1798 // Send key cancellation but do not consume the touch yet.
1799 // This is useful when the user swipes through from the virtual key area
1800 // into the main display surface.
1801 mCurrentVirtualKey.down = false;
1802 if (!mCurrentVirtualKey.ignored) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08001803 if (DEBUG_VIRTUAL_KEYS) {
1804 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1805 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1806 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001807 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001808 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1809 AKEY_EVENT_FLAG_CANCELED);
1810 }
1811 }
1812
1813 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1814 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1815 // Pointer just went down. Check for virtual key press or off-screen touches.
1816 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1817 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001818 // Skip checking whether the pointer is inside the physical frame if the device is in
1819 // unscaled mode.
1820 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1821 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001822 // If exactly one pointer went down, check for virtual key hit.
1823 // Otherwise we will drop the entire stroke.
1824 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1825 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1826 if (virtualKey) {
1827 mCurrentVirtualKey.down = true;
1828 mCurrentVirtualKey.downTime = when;
1829 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1830 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1831 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001832 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1833 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001834
1835 if (!mCurrentVirtualKey.ignored) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08001836 if (DEBUG_VIRTUAL_KEYS) {
1837 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1838 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1839 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001840 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001841 AKEY_EVENT_FLAG_FROM_SYSTEM |
1842 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1843 }
1844 }
1845 }
1846 return true;
1847 }
1848 }
1849
1850 // Disable all virtual key touches that happen within a short time interval of the
1851 // most recent touch within the screen area. The idea is to filter out stray
1852 // virtual key presses when interacting with the touch screen.
1853 //
1854 // Problems we're trying to solve:
1855 //
1856 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1857 // virtual key area that is implemented by a separate touch panel and accidentally
1858 // triggers a virtual key.
1859 //
1860 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1861 // area and accidentally triggers a virtual key. This often happens when virtual keys
1862 // are layed out below the screen near to where the on screen keyboard's space bar
1863 // is displayed.
1864 if (mConfig.virtualKeyQuietTime > 0 &&
1865 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001866 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001867 }
1868 return false;
1869}
1870
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001871void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001872 int32_t keyEventAction, int32_t keyEventFlags) {
1873 int32_t keyCode = mCurrentVirtualKey.keyCode;
1874 int32_t scanCode = mCurrentVirtualKey.scanCode;
1875 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001876 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001877 policyFlags |= POLICY_FLAG_VIRTUAL;
1878
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001879 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1880 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1881 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001882 getListener().notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001883}
1884
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001885void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001886 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1887 if (!currentIdBits.isEmpty()) {
1888 int32_t metaState = getContext()->getGlobalMetaState();
1889 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001890 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1891 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001892 mCurrentCookedState.cookedPointerData.pointerProperties,
1893 mCurrentCookedState.cookedPointerData.pointerCoords,
1894 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1895 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1896 mCurrentMotionAborted = true;
1897 }
1898}
1899
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001900void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001901 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1902 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1903 int32_t metaState = getContext()->getGlobalMetaState();
1904 int32_t buttonState = mCurrentCookedState.buttonState;
1905
1906 if (currentIdBits == lastIdBits) {
1907 if (!currentIdBits.isEmpty()) {
1908 // No pointer id changes so this is a move event.
1909 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001910 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1911 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001912 mCurrentCookedState.cookedPointerData.pointerProperties,
1913 mCurrentCookedState.cookedPointerData.pointerCoords,
1914 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1915 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1916 }
1917 } else {
1918 // There may be pointers going up and pointers going down and pointers moving
1919 // all at the same time.
1920 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1921 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1922 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1923 BitSet32 dispatchedIdBits(lastIdBits.value);
1924
1925 // Update last coordinates of pointers that have moved so that we observe the new
1926 // pointer positions at the same time as other pointers that have just gone up.
1927 bool moveNeeded =
1928 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1929 mCurrentCookedState.cookedPointerData.pointerCoords,
1930 mCurrentCookedState.cookedPointerData.idToIndex,
1931 mLastCookedState.cookedPointerData.pointerProperties,
1932 mLastCookedState.cookedPointerData.pointerCoords,
1933 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1934 if (buttonState != mLastCookedState.buttonState) {
1935 moveNeeded = true;
1936 }
1937
1938 // Dispatch pointer up events.
1939 while (!upIdBits.isEmpty()) {
1940 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001941 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001942 if (isCanceled) {
1943 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1944 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001945 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001946 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001947 mLastCookedState.cookedPointerData.pointerProperties,
1948 mLastCookedState.cookedPointerData.pointerCoords,
1949 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1950 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1951 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001952 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001953 }
1954
1955 // Dispatch move events if any of the remaining pointers moved from their old locations.
1956 // Although applications receive new locations as part of individual pointer up
1957 // events, they do not generally handle them except when presented in a move event.
1958 if (moveNeeded && !moveIdBits.isEmpty()) {
1959 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001960 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1961 metaState, buttonState, 0,
1962 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001963 mCurrentCookedState.cookedPointerData.pointerCoords,
1964 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1965 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1966 }
1967
1968 // Dispatch pointer down events using the new pointer locations.
1969 while (!downIdBits.isEmpty()) {
1970 uint32_t downId = downIdBits.clearFirstMarkedBit();
1971 dispatchedIdBits.markBit(downId);
1972
1973 if (dispatchedIdBits.count() == 1) {
1974 // First pointer is going down. Set down time.
1975 mDownTime = when;
1976 }
1977
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001978 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
1979 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001980 mCurrentCookedState.cookedPointerData.pointerProperties,
1981 mCurrentCookedState.cookedPointerData.pointerCoords,
1982 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1983 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1984 }
1985 }
1986}
1987
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001988void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001989 if (mSentHoverEnter &&
1990 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1991 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1992 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001993 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
1994 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001995 mLastCookedState.cookedPointerData.pointerProperties,
1996 mLastCookedState.cookedPointerData.pointerCoords,
1997 mLastCookedState.cookedPointerData.idToIndex,
1998 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1999 mOrientedYPrecision, mDownTime);
2000 mSentHoverEnter = false;
2001 }
2002}
2003
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002004void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2005 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002006 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2007 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2008 int32_t metaState = getContext()->getGlobalMetaState();
2009 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002010 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2011 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002012 mCurrentCookedState.cookedPointerData.pointerProperties,
2013 mCurrentCookedState.cookedPointerData.pointerCoords,
2014 mCurrentCookedState.cookedPointerData.idToIndex,
2015 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2016 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2017 mSentHoverEnter = true;
2018 }
2019
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002020 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2021 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002022 mCurrentCookedState.cookedPointerData.pointerProperties,
2023 mCurrentCookedState.cookedPointerData.pointerCoords,
2024 mCurrentCookedState.cookedPointerData.idToIndex,
2025 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2026 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2027 }
2028}
2029
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002030void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002031 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2032 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2033 const int32_t metaState = getContext()->getGlobalMetaState();
2034 int32_t buttonState = mLastCookedState.buttonState;
2035 while (!releasedButtons.isEmpty()) {
2036 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2037 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002038 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002039 actionButton, 0, metaState, buttonState, 0,
2040 mCurrentCookedState.cookedPointerData.pointerProperties,
2041 mCurrentCookedState.cookedPointerData.pointerCoords,
2042 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2043 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2044 }
2045}
2046
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002047void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002048 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2049 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2050 const int32_t metaState = getContext()->getGlobalMetaState();
2051 int32_t buttonState = mLastCookedState.buttonState;
2052 while (!pressedButtons.isEmpty()) {
2053 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2054 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002055 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2056 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002057 mCurrentCookedState.cookedPointerData.pointerProperties,
2058 mCurrentCookedState.cookedPointerData.pointerCoords,
2059 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2060 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2061 }
2062}
2063
2064const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2065 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2066 return cookedPointerData.touchingIdBits;
2067 }
2068 return cookedPointerData.hoveringIdBits;
2069}
2070
2071void TouchInputMapper::cookPointerData() {
2072 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2073
2074 mCurrentCookedState.cookedPointerData.clear();
2075 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2076 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2077 mCurrentRawState.rawPointerData.hoveringIdBits;
2078 mCurrentCookedState.cookedPointerData.touchingIdBits =
2079 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002080 mCurrentCookedState.cookedPointerData.canceledIdBits =
2081 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002082
2083 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2084 mCurrentCookedState.buttonState = 0;
2085 } else {
2086 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2087 }
2088
2089 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002090 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002091 for (uint32_t i = 0; i < currentPointerCount; i++) {
2092 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2093
2094 // Size
2095 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2096 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002097 case Calibration::SizeCalibration::GEOMETRIC:
2098 case Calibration::SizeCalibration::DIAMETER:
2099 case Calibration::SizeCalibration::BOX:
2100 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002101 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2102 touchMajor = in.touchMajor;
2103 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2104 toolMajor = in.toolMajor;
2105 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2106 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2107 : in.touchMajor;
2108 } else if (mRawPointerAxes.touchMajor.valid) {
2109 toolMajor = touchMajor = in.touchMajor;
2110 toolMinor = touchMinor =
2111 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2112 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2113 : in.touchMajor;
2114 } else if (mRawPointerAxes.toolMajor.valid) {
2115 touchMajor = toolMajor = in.toolMajor;
2116 touchMinor = toolMinor =
2117 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2118 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2119 : in.toolMajor;
2120 } else {
2121 ALOG_ASSERT(false,
2122 "No touch or tool axes. "
2123 "Size calibration should have been resolved to NONE.");
2124 touchMajor = 0;
2125 touchMinor = 0;
2126 toolMajor = 0;
2127 toolMinor = 0;
2128 size = 0;
2129 }
2130
2131 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2132 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2133 if (touchingCount > 1) {
2134 touchMajor /= touchingCount;
2135 touchMinor /= touchingCount;
2136 toolMajor /= touchingCount;
2137 toolMinor /= touchingCount;
2138 size /= touchingCount;
2139 }
2140 }
2141
Michael Wright227c5542020-07-02 18:30:52 +01002142 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002143 touchMajor *= mGeometricScale;
2144 touchMinor *= mGeometricScale;
2145 toolMajor *= mGeometricScale;
2146 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002147 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002148 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2149 touchMinor = touchMajor;
2150 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2151 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002152 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002153 touchMinor = touchMajor;
2154 toolMinor = toolMajor;
2155 }
2156
2157 mCalibration.applySizeScaleAndBias(&touchMajor);
2158 mCalibration.applySizeScaleAndBias(&touchMinor);
2159 mCalibration.applySizeScaleAndBias(&toolMajor);
2160 mCalibration.applySizeScaleAndBias(&toolMinor);
2161 size *= mSizeScale;
2162 break;
2163 default:
2164 touchMajor = 0;
2165 touchMinor = 0;
2166 toolMajor = 0;
2167 toolMinor = 0;
2168 size = 0;
2169 break;
2170 }
2171
2172 // Pressure
2173 float pressure;
2174 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002175 case Calibration::PressureCalibration::PHYSICAL:
2176 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002177 pressure = in.pressure * mPressureScale;
2178 break;
2179 default:
2180 pressure = in.isHovering ? 0 : 1;
2181 break;
2182 }
2183
2184 // Tilt and Orientation
2185 float tilt;
2186 float orientation;
2187 if (mHaveTilt) {
2188 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2189 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2190 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2191 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2192 } else {
2193 tilt = 0;
2194
2195 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002196 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002197 orientation = in.orientation * mOrientationScale;
2198 break;
Michael Wright227c5542020-07-02 18:30:52 +01002199 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002200 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2201 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2202 if (c1 != 0 || c2 != 0) {
2203 orientation = atan2f(c1, c2) * 0.5f;
2204 float confidence = hypotf(c1, c2);
2205 float scale = 1.0f + confidence / 16.0f;
2206 touchMajor *= scale;
2207 touchMinor /= scale;
2208 toolMajor *= scale;
2209 toolMinor /= scale;
2210 } else {
2211 orientation = 0;
2212 }
2213 break;
2214 }
2215 default:
2216 orientation = 0;
2217 }
2218 }
2219
2220 // Distance
2221 float distance;
2222 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002223 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002224 distance = in.distance * mDistanceScale;
2225 break;
2226 default:
2227 distance = 0;
2228 }
2229
2230 // Coverage
2231 int32_t rawLeft, rawTop, rawRight, rawBottom;
2232 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002233 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002234 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2235 rawRight = in.toolMinor & 0x0000ffff;
2236 rawBottom = in.toolMajor & 0x0000ffff;
2237 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2238 break;
2239 default:
2240 rawLeft = rawTop = rawRight = rawBottom = 0;
2241 break;
2242 }
2243
2244 // Adjust X,Y coords for device calibration
2245 // TODO: Adjust coverage coords?
2246 float xTransformed = in.x, yTransformed = in.y;
2247 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002248 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002249
Prabir Pradhan1728b212021-10-19 16:00:03 -07002250 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002251 float left, top, right, bottom;
2252
Prabir Pradhan1728b212021-10-19 16:00:03 -07002253 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002254 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002255 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2256 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2257 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2258 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002259 orientation -= M_PI_2;
2260 if (mOrientedRanges.haveOrientation &&
2261 orientation < mOrientedRanges.orientation.min) {
2262 orientation +=
2263 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2264 }
2265 break;
2266 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002267 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2268 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002269 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2270 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002271 orientation -= M_PI;
2272 if (mOrientedRanges.haveOrientation &&
2273 orientation < mOrientedRanges.orientation.min) {
2274 orientation +=
2275 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2276 }
2277 break;
2278 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002279 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2280 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002281 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2282 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002283 orientation += M_PI_2;
2284 if (mOrientedRanges.haveOrientation &&
2285 orientation > mOrientedRanges.orientation.max) {
2286 orientation -=
2287 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2288 }
2289 break;
2290 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002291 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2292 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2293 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2294 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002295 break;
2296 }
2297
2298 // Write output coords.
2299 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2300 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002301 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2302 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2304 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2305 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2306 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2307 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2308 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2309 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002310 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002311 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2312 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2313 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2314 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2315 } else {
2316 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2317 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2318 }
2319
Chris Ye364fdb52020-08-05 15:07:56 -07002320 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002321 uint32_t id = in.id;
2322 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2323 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2324 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2325 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2326 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2327 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2328 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2329 }
2330
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002331 // Write output properties.
2332 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002333 properties.clear();
2334 properties.id = id;
2335 properties.toolType = in.toolType;
2336
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002337 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002338 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002339 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002340 }
2341}
2342
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002343void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 PointerUsage pointerUsage) {
2345 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002346 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 mPointerUsage = pointerUsage;
2348 }
2349
2350 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002351 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002352 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353 break;
Michael Wright227c5542020-07-02 18:30:52 +01002354 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002355 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 break;
Michael Wright227c5542020-07-02 18:30:52 +01002357 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002358 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 break;
Michael Wright227c5542020-07-02 18:30:52 +01002360 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 break;
2362 }
2363}
2364
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002365void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002367 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002368 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 break;
Michael Wright227c5542020-07-02 18:30:52 +01002370 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002371 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 break;
Michael Wright227c5542020-07-02 18:30:52 +01002373 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002374 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 break;
Michael Wright227c5542020-07-02 18:30:52 +01002376 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 break;
2378 }
2379
Michael Wright227c5542020-07-02 18:30:52 +01002380 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381}
2382
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002383void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2384 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 // Update current gesture coordinates.
2386 bool cancelPreviousGesture, finishPreviousGesture;
2387 bool sendEvents =
2388 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2389 if (!sendEvents) {
2390 return;
2391 }
2392 if (finishPreviousGesture) {
2393 cancelPreviousGesture = false;
2394 }
2395
2396 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002397 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002398 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002399 if (finishPreviousGesture || cancelPreviousGesture) {
2400 mPointerController->clearSpots();
2401 }
2402
Michael Wright227c5542020-07-02 18:30:52 +01002403 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002404 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2405 mPointerGesture.currentGestureIdToIndex,
2406 mPointerGesture.currentGestureIdBits,
2407 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002408 }
2409 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002410 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 }
2412
2413 // Show or hide the pointer if needed.
2414 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002415 case PointerGesture::Mode::NEUTRAL:
2416 case PointerGesture::Mode::QUIET:
2417 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2418 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002420 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002421 }
2422 break;
Michael Wright227c5542020-07-02 18:30:52 +01002423 case PointerGesture::Mode::TAP:
2424 case PointerGesture::Mode::TAP_DRAG:
2425 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2426 case PointerGesture::Mode::HOVER:
2427 case PointerGesture::Mode::PRESS:
2428 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429 // Unfade the pointer when the current gesture manipulates the
2430 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002431 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 break;
Michael Wright227c5542020-07-02 18:30:52 +01002433 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 // Fade the pointer when the current gesture manipulates a different
2435 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002436 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002437 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002438 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002439 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 }
2441 break;
2442 }
2443
2444 // Send events!
2445 int32_t metaState = getContext()->getGlobalMetaState();
2446 int32_t buttonState = mCurrentCookedState.buttonState;
2447
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002448 uint32_t flags = 0;
2449
2450 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2451 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2452 }
2453
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454 // Update last coordinates of pointers that have moved so that we observe the new
2455 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002456 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2457 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2458 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2459 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2460 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2461 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462 bool moveNeeded = false;
2463 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2464 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2465 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2466 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2467 mPointerGesture.lastGestureIdBits.value);
2468 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2469 mPointerGesture.currentGestureCoords,
2470 mPointerGesture.currentGestureIdToIndex,
2471 mPointerGesture.lastGestureProperties,
2472 mPointerGesture.lastGestureCoords,
2473 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2474 if (buttonState != mLastCookedState.buttonState) {
2475 moveNeeded = true;
2476 }
2477 }
2478
2479 // Send motion events for all pointers that went up or were canceled.
2480 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2481 if (!dispatchedGestureIdBits.isEmpty()) {
2482 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002483 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2484 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2486 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2487 mPointerGesture.downTime);
2488
2489 dispatchedGestureIdBits.clear();
2490 } else {
2491 BitSet32 upGestureIdBits;
2492 if (finishPreviousGesture) {
2493 upGestureIdBits = dispatchedGestureIdBits;
2494 } else {
2495 upGestureIdBits.value =
2496 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2497 }
2498 while (!upGestureIdBits.isEmpty()) {
2499 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2500
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002501 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002502 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002503 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 mPointerGesture.lastGestureCoords,
2505 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2506 0, mPointerGesture.downTime);
2507
2508 dispatchedGestureIdBits.clearBit(id);
2509 }
2510 }
2511 }
2512
2513 // Send motion events for all pointers that moved.
2514 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002515 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002516 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002517 mPointerGesture.currentGestureProperties,
2518 mPointerGesture.currentGestureCoords,
2519 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2520 mPointerGesture.downTime);
2521 }
2522
2523 // Send motion events for all pointers that went down.
2524 if (down) {
2525 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2526 ~dispatchedGestureIdBits.value);
2527 while (!downGestureIdBits.isEmpty()) {
2528 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2529 dispatchedGestureIdBits.markBit(id);
2530
2531 if (dispatchedGestureIdBits.count() == 1) {
2532 mPointerGesture.downTime = when;
2533 }
2534
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002535 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002536 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002537 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002538 mPointerGesture.currentGestureCoords,
2539 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2540 0, mPointerGesture.downTime);
2541 }
2542 }
2543
2544 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002545 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002546 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2547 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002548 mPointerGesture.currentGestureProperties,
2549 mPointerGesture.currentGestureCoords,
2550 mPointerGesture.currentGestureIdToIndex,
2551 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2552 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2553 // Synthesize a hover move event after all pointers go up to indicate that
2554 // the pointer is hovering again even if the user is not currently touching
2555 // the touch pad. This ensures that a view will receive a fresh hover enter
2556 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002557 float x, y;
2558 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002559
2560 PointerProperties pointerProperties;
2561 pointerProperties.clear();
2562 pointerProperties.id = 0;
2563 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2564
2565 PointerCoords pointerCoords;
2566 pointerCoords.clear();
2567 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2568 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2569
2570 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002571 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002572 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002573 metaState, buttonState, MotionClassification::NONE,
2574 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2575 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002576 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002577 }
2578
2579 // Update state.
2580 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2581 if (!down) {
2582 mPointerGesture.lastGestureIdBits.clear();
2583 } else {
2584 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2585 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2586 uint32_t id = idBits.clearFirstMarkedBit();
2587 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2588 mPointerGesture.lastGestureProperties[index].copyFrom(
2589 mPointerGesture.currentGestureProperties[index]);
2590 mPointerGesture.lastGestureCoords[index].copyFrom(
2591 mPointerGesture.currentGestureCoords[index]);
2592 mPointerGesture.lastGestureIdToIndex[id] = index;
2593 }
2594 }
2595}
2596
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002597void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002598 // Cancel previously dispatches pointers.
2599 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2600 int32_t metaState = getContext()->getGlobalMetaState();
2601 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002602 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2603 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002604 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2605 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2606 0, 0, mPointerGesture.downTime);
2607 }
2608
2609 // Reset the current pointer gesture.
2610 mPointerGesture.reset();
2611 mPointerVelocityControl.reset();
2612
2613 // Remove any current spots.
2614 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002615 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002616 mPointerController->clearSpots();
2617 }
2618}
2619
2620bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2621 bool* outFinishPreviousGesture, bool isTimeout) {
2622 *outCancelPreviousGesture = false;
2623 *outFinishPreviousGesture = false;
2624
2625 // Handle TAP timeout.
2626 if (isTimeout) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002627 if (DEBUG_GESTURES) {
2628 ALOGD("Gestures: Processing timeout");
2629 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002630
Michael Wright227c5542020-07-02 18:30:52 +01002631 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002632 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2633 // The tap/drag timeout has not yet expired.
2634 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2635 mConfig.pointerGestureTapDragInterval);
2636 } else {
2637 // The tap is finished.
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002638 if (DEBUG_GESTURES) {
2639 ALOGD("Gestures: TAP finished");
2640 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002641 *outFinishPreviousGesture = true;
2642
2643 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002644 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002645 mPointerGesture.currentGestureIdBits.clear();
2646
2647 mPointerVelocityControl.reset();
2648 return true;
2649 }
2650 }
2651
2652 // We did not handle this timeout.
2653 return false;
2654 }
2655
2656 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2657 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2658
2659 // Update the velocity tracker.
2660 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002661 std::vector<VelocityTracker::Position> positions;
2662 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002663 uint32_t id = idBits.clearFirstMarkedBit();
2664 const RawPointerData::Pointer& pointer =
2665 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002666 float x = pointer.x * mPointerXMovementScale;
2667 float y = pointer.y * mPointerYMovementScale;
2668 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002669 }
2670 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2671 positions);
2672 }
2673
2674 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2675 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002676 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2677 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2678 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002679 mPointerGesture.resetTap();
2680 }
2681
2682 // Pick a new active touch id if needed.
2683 // Choose an arbitrary pointer that just went down, if there is one.
2684 // Otherwise choose an arbitrary remaining pointer.
2685 // This guarantees we always have an active touch id when there is at least one pointer.
2686 // We keep the same active touch id for as long as possible.
2687 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2688 int32_t activeTouchId = lastActiveTouchId;
2689 if (activeTouchId < 0) {
2690 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2691 activeTouchId = mPointerGesture.activeTouchId =
2692 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2693 mPointerGesture.firstTouchTime = when;
2694 }
2695 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2696 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2697 activeTouchId = mPointerGesture.activeTouchId =
2698 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2699 } else {
2700 activeTouchId = mPointerGesture.activeTouchId = -1;
2701 }
2702 }
2703
2704 // Determine whether we are in quiet time.
2705 bool isQuietTime = false;
2706 if (activeTouchId < 0) {
2707 mPointerGesture.resetQuietTime();
2708 } else {
2709 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2710 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002711 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2712 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2713 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002714 currentFingerCount < 2) {
2715 // Enter quiet time when exiting swipe or freeform state.
2716 // This is to prevent accidentally entering the hover state and flinging the
2717 // pointer when finishing a swipe and there is still one pointer left onscreen.
2718 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002719 } else if (mPointerGesture.lastGestureMode ==
2720 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002721 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2722 // Enter quiet time when releasing the button and there are still two or more
2723 // fingers down. This may indicate that one finger was used to press the button
2724 // but it has not gone up yet.
2725 isQuietTime = true;
2726 }
2727 if (isQuietTime) {
2728 mPointerGesture.quietTime = when;
2729 }
2730 }
2731 }
2732
2733 // Switch states based on button and pointer state.
2734 if (isQuietTime) {
2735 // Case 1: Quiet time. (QUIET)
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002736 if (DEBUG_GESTURES) {
2737 ALOGD("Gestures: QUIET for next %0.3fms",
2738 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2739 0.000001f);
2740 }
Michael Wright227c5542020-07-02 18:30:52 +01002741 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002742 *outFinishPreviousGesture = true;
2743 }
2744
2745 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002746 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002747 mPointerGesture.currentGestureIdBits.clear();
2748
2749 mPointerVelocityControl.reset();
2750 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2751 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2752 // The pointer follows the active touch point.
2753 // Emit DOWN, MOVE, UP events at the pointer location.
2754 //
2755 // Only the active touch matters; other fingers are ignored. This policy helps
2756 // to handle the case where the user places a second finger on the touch pad
2757 // to apply the necessary force to depress an integrated button below the surface.
2758 // We don't want the second finger to be delivered to applications.
2759 //
2760 // For this to work well, we need to make sure to track the pointer that is really
2761 // active. If the user first puts one finger down to click then adds another
2762 // finger to drag then the active pointer should switch to the finger that is
2763 // being dragged.
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002764 if (DEBUG_GESTURES) {
2765 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2766 "currentFingerCount=%d",
2767 activeTouchId, currentFingerCount);
2768 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002769 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002770 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002771 *outFinishPreviousGesture = true;
2772 mPointerGesture.activeGestureId = 0;
2773 }
2774
2775 // Switch pointers if needed.
2776 // Find the fastest pointer and follow it.
2777 if (activeTouchId >= 0 && currentFingerCount > 1) {
2778 int32_t bestId = -1;
2779 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2780 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2781 uint32_t id = idBits.clearFirstMarkedBit();
2782 float vx, vy;
2783 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2784 float speed = hypotf(vx, vy);
2785 if (speed > bestSpeed) {
2786 bestId = id;
2787 bestSpeed = speed;
2788 }
2789 }
2790 }
2791 if (bestId >= 0 && bestId != activeTouchId) {
2792 mPointerGesture.activeTouchId = activeTouchId = bestId;
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002793 if (DEBUG_GESTURES) {
2794 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2795 "bestId=%d, bestSpeed=%0.3f",
2796 bestId, bestSpeed);
2797 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002798 }
2799 }
2800
2801 float deltaX = 0, deltaY = 0;
2802 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2803 const RawPointerData::Pointer& currentPointer =
2804 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2805 const RawPointerData::Pointer& lastPointer =
2806 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2807 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2808 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2809
Prabir Pradhan1728b212021-10-19 16:00:03 -07002810 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002811 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2812
2813 // Move the pointer using a relative motion.
2814 // When using spots, the click will occur at the position of the anchor
2815 // spot and all other spots will move there.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002816 mPointerController->move(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002817 } else {
2818 mPointerVelocityControl.reset();
2819 }
2820
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002821 float x, y;
2822 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823
Michael Wright227c5542020-07-02 18:30:52 +01002824 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825 mPointerGesture.currentGestureIdBits.clear();
2826 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2827 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2828 mPointerGesture.currentGestureProperties[0].clear();
2829 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2830 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2831 mPointerGesture.currentGestureCoords[0].clear();
2832 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2833 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2834 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2835 } else if (currentFingerCount == 0) {
2836 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002837 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002838 *outFinishPreviousGesture = true;
2839 }
2840
2841 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2842 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2843 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002844 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2845 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002846 lastFingerCount == 1) {
2847 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002848 float x, y;
2849 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002850 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2851 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002852 if (DEBUG_GESTURES) {
2853 ALOGD("Gestures: TAP");
2854 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855
2856 mPointerGesture.tapUpTime = when;
2857 getContext()->requestTimeoutAtTime(when +
2858 mConfig.pointerGestureTapDragInterval);
2859
2860 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002861 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002862 mPointerGesture.currentGestureIdBits.clear();
2863 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2864 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2865 mPointerGesture.currentGestureProperties[0].clear();
2866 mPointerGesture.currentGestureProperties[0].id =
2867 mPointerGesture.activeGestureId;
2868 mPointerGesture.currentGestureProperties[0].toolType =
2869 AMOTION_EVENT_TOOL_TYPE_FINGER;
2870 mPointerGesture.currentGestureCoords[0].clear();
2871 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2872 mPointerGesture.tapX);
2873 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2874 mPointerGesture.tapY);
2875 mPointerGesture.currentGestureCoords[0]
2876 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2877
2878 tapped = true;
2879 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002880 if (DEBUG_GESTURES) {
2881 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2882 y - mPointerGesture.tapY);
2883 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884 }
2885 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002886 if (DEBUG_GESTURES) {
2887 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2888 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2889 (when - mPointerGesture.tapDownTime) * 0.000001f);
2890 } else {
2891 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2892 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002893 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002894 }
2895 }
2896
2897 mPointerVelocityControl.reset();
2898
2899 if (!tapped) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002900 if (DEBUG_GESTURES) {
2901 ALOGD("Gestures: NEUTRAL");
2902 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002904 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002905 mPointerGesture.currentGestureIdBits.clear();
2906 }
2907 } else if (currentFingerCount == 1) {
2908 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2909 // The pointer follows the active touch point.
2910 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2911 // When in TAP_DRAG, emit MOVE events at the pointer location.
2912 ALOG_ASSERT(activeTouchId >= 0);
2913
Michael Wright227c5542020-07-02 18:30:52 +01002914 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2915 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002917 float x, y;
2918 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2920 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002921 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002923 if (DEBUG_GESTURES) {
2924 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2925 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2926 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002927 }
2928 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002929 if (DEBUG_GESTURES) {
2930 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2931 (when - mPointerGesture.tapUpTime) * 0.000001f);
2932 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002933 }
Michael Wright227c5542020-07-02 18:30:52 +01002934 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2935 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002936 }
2937
2938 float deltaX = 0, deltaY = 0;
2939 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2940 const RawPointerData::Pointer& currentPointer =
2941 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2942 const RawPointerData::Pointer& lastPointer =
2943 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2944 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2945 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2946
Prabir Pradhan1728b212021-10-19 16:00:03 -07002947 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002948 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2949
2950 // Move the pointer using a relative motion.
2951 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002952 mPointerController->move(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002953 } else {
2954 mPointerVelocityControl.reset();
2955 }
2956
2957 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002958 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002959 if (DEBUG_GESTURES) {
2960 ALOGD("Gestures: TAP_DRAG");
2961 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002962 down = true;
2963 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002964 if (DEBUG_GESTURES) {
2965 ALOGD("Gestures: HOVER");
2966 }
Michael Wright227c5542020-07-02 18:30:52 +01002967 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 *outFinishPreviousGesture = true;
2969 }
2970 mPointerGesture.activeGestureId = 0;
2971 down = false;
2972 }
2973
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002974 float x, y;
2975 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002976
2977 mPointerGesture.currentGestureIdBits.clear();
2978 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2979 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2980 mPointerGesture.currentGestureProperties[0].clear();
2981 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2982 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2983 mPointerGesture.currentGestureCoords[0].clear();
2984 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2985 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2986 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2987 down ? 1.0f : 0.0f);
2988
2989 if (lastFingerCount == 0 && currentFingerCount != 0) {
2990 mPointerGesture.resetTap();
2991 mPointerGesture.tapDownTime = when;
2992 mPointerGesture.tapX = x;
2993 mPointerGesture.tapY = y;
2994 }
2995 } else {
2996 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2997 // We need to provide feedback for each finger that goes down so we cannot wait
2998 // for the fingers to move before deciding what to do.
2999 //
3000 // The ambiguous case is deciding what to do when there are two fingers down but they
3001 // have not moved enough to determine whether they are part of a drag or part of a
3002 // freeform gesture, or just a press or long-press at the pointer location.
3003 //
3004 // When there are two fingers we start with the PRESS hypothesis and we generate a
3005 // down at the pointer location.
3006 //
3007 // When the two fingers move enough or when additional fingers are added, we make
3008 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3009 ALOG_ASSERT(activeTouchId >= 0);
3010
3011 bool settled = when >=
3012 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003013 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3014 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3015 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003016 *outFinishPreviousGesture = true;
3017 } else if (!settled && currentFingerCount > lastFingerCount) {
3018 // Additional pointers have gone down but not yet settled.
3019 // Reset the gesture.
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003020 if (DEBUG_GESTURES) {
3021 ALOGD("Gestures: Resetting gesture since additional pointers went down for "
3022 "MULTITOUCH, settle time remaining %0.3fms",
3023 (mPointerGesture.firstTouchTime +
3024 mConfig.pointerGestureMultitouchSettleInterval - when) *
3025 0.000001f);
3026 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003027 *outCancelPreviousGesture = true;
3028 } else {
3029 // Continue previous gesture.
3030 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3031 }
3032
3033 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003034 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003035 mPointerGesture.activeGestureId = 0;
3036 mPointerGesture.referenceIdBits.clear();
3037 mPointerVelocityControl.reset();
3038
3039 // Use the centroid and pointer location as the reference points for the gesture.
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003040 if (DEBUG_GESTURES) {
3041 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3042 "settle time remaining %0.3fms",
3043 (mPointerGesture.firstTouchTime +
3044 mConfig.pointerGestureMultitouchSettleInterval - when) *
3045 0.000001f);
3046 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047 mCurrentRawState.rawPointerData
3048 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3049 &mPointerGesture.referenceTouchY);
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003050 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3051 &mPointerGesture.referenceGestureY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003052 }
3053
3054 // Clear the reference deltas for fingers not yet included in the reference calculation.
3055 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3056 ~mPointerGesture.referenceIdBits.value);
3057 !idBits.isEmpty();) {
3058 uint32_t id = idBits.clearFirstMarkedBit();
3059 mPointerGesture.referenceDeltas[id].dx = 0;
3060 mPointerGesture.referenceDeltas[id].dy = 0;
3061 }
3062 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3063
3064 // Add delta for all fingers and calculate a common movement delta.
3065 float commonDeltaX = 0, commonDeltaY = 0;
3066 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3067 mCurrentCookedState.fingerIdBits.value);
3068 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3069 bool first = (idBits == commonIdBits);
3070 uint32_t id = idBits.clearFirstMarkedBit();
3071 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3072 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3073 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3074 delta.dx += cpd.x - lpd.x;
3075 delta.dy += cpd.y - lpd.y;
3076
3077 if (first) {
3078 commonDeltaX = delta.dx;
3079 commonDeltaY = delta.dy;
3080 } else {
3081 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3082 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3083 }
3084 }
3085
3086 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003087 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003088 float dist[MAX_POINTER_ID + 1];
3089 int32_t distOverThreshold = 0;
3090 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3091 uint32_t id = idBits.clearFirstMarkedBit();
3092 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3093 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3094 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3095 distOverThreshold += 1;
3096 }
3097 }
3098
3099 // Only transition when at least two pointers have moved further than
3100 // the minimum distance threshold.
3101 if (distOverThreshold >= 2) {
3102 if (currentFingerCount > 2) {
3103 // There are more than two pointers, switch to FREEFORM.
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003104 if (DEBUG_GESTURES) {
3105 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3106 currentFingerCount);
3107 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003108 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003109 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003110 } else {
3111 // There are exactly two pointers.
3112 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3113 uint32_t id1 = idBits.clearFirstMarkedBit();
3114 uint32_t id2 = idBits.firstMarkedBit();
3115 const RawPointerData::Pointer& p1 =
3116 mCurrentRawState.rawPointerData.pointerForId(id1);
3117 const RawPointerData::Pointer& p2 =
3118 mCurrentRawState.rawPointerData.pointerForId(id2);
3119 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3120 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3121 // There are two pointers but they are too far apart for a SWIPE,
3122 // switch to FREEFORM.
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003123 if (DEBUG_GESTURES) {
3124 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > "
3125 "%0.3f",
3126 mutualDistance, mPointerGestureMaxSwipeWidth);
3127 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003128 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003129 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003130 } else {
3131 // There are two pointers. Wait for both pointers to start moving
3132 // before deciding whether this is a SWIPE or FREEFORM gesture.
3133 float dist1 = dist[id1];
3134 float dist2 = dist[id2];
3135 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3136 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3137 // Calculate the dot product of the displacement vectors.
3138 // When the vectors are oriented in approximately the same direction,
3139 // the angle betweeen them is near zero and the cosine of the angle
3140 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3141 // mag(v2).
3142 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3143 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3144 float dx1 = delta1.dx * mPointerXZoomScale;
3145 float dy1 = delta1.dy * mPointerYZoomScale;
3146 float dx2 = delta2.dx * mPointerXZoomScale;
3147 float dy2 = delta2.dy * mPointerYZoomScale;
3148 float dot = dx1 * dx2 + dy1 * dy2;
3149 float cosine = dot / (dist1 * dist2); // denominator always > 0
3150 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3151 // Pointers are moving in the same direction. Switch to SWIPE.
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003152 if (DEBUG_GESTURES) {
3153 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3154 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3155 "cosine %0.3f >= %0.3f",
3156 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3157 mConfig.pointerGestureMultitouchMinDistance, cosine,
3158 mConfig.pointerGestureSwipeTransitionAngleCosine);
3159 }
Michael Wright227c5542020-07-02 18:30:52 +01003160 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003161 } else {
3162 // Pointers are moving in different directions. Switch to FREEFORM.
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003163 if (DEBUG_GESTURES) {
3164 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3165 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3166 "cosine %0.3f < %0.3f",
3167 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3168 mConfig.pointerGestureMultitouchMinDistance, cosine,
3169 mConfig.pointerGestureSwipeTransitionAngleCosine);
3170 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003171 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003172 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003173 }
3174 }
3175 }
3176 }
3177 }
Michael Wright227c5542020-07-02 18:30:52 +01003178 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003179 // Switch from SWIPE to FREEFORM if additional pointers go down.
3180 // Cancel previous gesture.
3181 if (currentFingerCount > 2) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003182 if (DEBUG_GESTURES) {
3183 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3184 currentFingerCount);
3185 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003186 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003187 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003188 }
3189 }
3190
3191 // Move the reference points based on the overall group motion of the fingers
3192 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003193 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003194 (commonDeltaX || commonDeltaY)) {
3195 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3196 uint32_t id = idBits.clearFirstMarkedBit();
3197 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3198 delta.dx = 0;
3199 delta.dy = 0;
3200 }
3201
3202 mPointerGesture.referenceTouchX += commonDeltaX;
3203 mPointerGesture.referenceTouchY += commonDeltaY;
3204
3205 commonDeltaX *= mPointerXMovementScale;
3206 commonDeltaY *= mPointerYMovementScale;
3207
Prabir Pradhan1728b212021-10-19 16:00:03 -07003208 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003209 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3210
3211 mPointerGesture.referenceGestureX += commonDeltaX;
3212 mPointerGesture.referenceGestureY += commonDeltaY;
3213 }
3214
3215 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003216 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3217 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003218 // PRESS or SWIPE mode.
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003219 if (DEBUG_GESTURES) {
3220 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3221 "activeGestureId=%d, currentTouchPointerCount=%d",
3222 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3223 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003224 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3225
3226 mPointerGesture.currentGestureIdBits.clear();
3227 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3228 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3229 mPointerGesture.currentGestureProperties[0].clear();
3230 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3231 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3232 mPointerGesture.currentGestureCoords[0].clear();
3233 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3234 mPointerGesture.referenceGestureX);
3235 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3236 mPointerGesture.referenceGestureY);
3237 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003238 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003239 // FREEFORM mode.
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003240 if (DEBUG_GESTURES) {
3241 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3242 "activeGestureId=%d, currentTouchPointerCount=%d",
3243 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3244 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003245 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3246
3247 mPointerGesture.currentGestureIdBits.clear();
3248
3249 BitSet32 mappedTouchIdBits;
3250 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003251 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003252 // Initially, assign the active gesture id to the active touch point
3253 // if there is one. No other touch id bits are mapped yet.
3254 if (!*outCancelPreviousGesture) {
3255 mappedTouchIdBits.markBit(activeTouchId);
3256 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3257 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3258 mPointerGesture.activeGestureId;
3259 } else {
3260 mPointerGesture.activeGestureId = -1;
3261 }
3262 } else {
3263 // Otherwise, assume we mapped all touches from the previous frame.
3264 // Reuse all mappings that are still applicable.
3265 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3266 mCurrentCookedState.fingerIdBits.value;
3267 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3268
3269 // Check whether we need to choose a new active gesture id because the
3270 // current went went up.
3271 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3272 ~mCurrentCookedState.fingerIdBits.value);
3273 !upTouchIdBits.isEmpty();) {
3274 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3275 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3276 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3277 mPointerGesture.activeGestureId = -1;
3278 break;
3279 }
3280 }
3281 }
3282
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003283 if (DEBUG_GESTURES) {
3284 ALOGD("Gestures: FREEFORM follow up "
3285 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3286 "activeGestureId=%d",
3287 mappedTouchIdBits.value, usedGestureIdBits.value,
3288 mPointerGesture.activeGestureId);
3289 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003290
3291 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3292 for (uint32_t i = 0; i < currentFingerCount; i++) {
3293 uint32_t touchId = idBits.clearFirstMarkedBit();
3294 uint32_t gestureId;
3295 if (!mappedTouchIdBits.hasBit(touchId)) {
3296 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3297 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003298 if (DEBUG_GESTURES) {
3299 ALOGD("Gestures: FREEFORM "
3300 "new mapping for touch id %d -> gesture id %d",
3301 touchId, gestureId);
3302 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003303 } else {
3304 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003305 if (DEBUG_GESTURES) {
3306 ALOGD("Gestures: FREEFORM "
3307 "existing mapping for touch id %d -> gesture id %d",
3308 touchId, gestureId);
3309 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003310 }
3311 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3312 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3313
3314 const RawPointerData::Pointer& pointer =
3315 mCurrentRawState.rawPointerData.pointerForId(touchId);
3316 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3317 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07003318 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003319
3320 mPointerGesture.currentGestureProperties[i].clear();
3321 mPointerGesture.currentGestureProperties[i].id = gestureId;
3322 mPointerGesture.currentGestureProperties[i].toolType =
3323 AMOTION_EVENT_TOOL_TYPE_FINGER;
3324 mPointerGesture.currentGestureCoords[i].clear();
3325 mPointerGesture.currentGestureCoords[i]
3326 .setAxisValue(AMOTION_EVENT_AXIS_X,
3327 mPointerGesture.referenceGestureX + deltaX);
3328 mPointerGesture.currentGestureCoords[i]
3329 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3330 mPointerGesture.referenceGestureY + deltaY);
3331 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3332 1.0f);
3333 }
3334
3335 if (mPointerGesture.activeGestureId < 0) {
3336 mPointerGesture.activeGestureId =
3337 mPointerGesture.currentGestureIdBits.firstMarkedBit();
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003338 if (DEBUG_GESTURES) {
3339 ALOGD("Gestures: FREEFORM new activeGestureId=%d",
3340 mPointerGesture.activeGestureId);
3341 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003342 }
3343 }
3344 }
3345
3346 mPointerController->setButtonState(mCurrentRawState.buttonState);
3347
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003348 if (DEBUG_GESTURES) {
3349 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3350 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3351 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3352 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3353 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3354 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3355 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3356 uint32_t id = idBits.clearFirstMarkedBit();
3357 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3358 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3359 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3360 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3361 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3362 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3363 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3364 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3365 }
3366 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3367 uint32_t id = idBits.clearFirstMarkedBit();
3368 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3369 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3370 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3371 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3372 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3373 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3374 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3375 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3376 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003377 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003378 return true;
3379}
3380
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003381void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003382 mPointerSimple.currentCoords.clear();
3383 mPointerSimple.currentProperties.clear();
3384
3385 bool down, hovering;
3386 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3387 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3388 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003389 mPointerController
3390 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3391 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003392
3393 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3394 down = !hovering;
3395
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003396 float x, y;
3397 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003398 mPointerSimple.currentCoords.copyFrom(
3399 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3400 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3401 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3402 mPointerSimple.currentProperties.id = 0;
3403 mPointerSimple.currentProperties.toolType =
3404 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3405 } else {
3406 down = false;
3407 hovering = false;
3408 }
3409
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003410 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003411}
3412
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003413void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3414 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003415}
3416
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003417void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003418 mPointerSimple.currentCoords.clear();
3419 mPointerSimple.currentProperties.clear();
3420
3421 bool down, hovering;
3422 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3423 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3424 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3425 float deltaX = 0, deltaY = 0;
3426 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3427 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3428 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3429 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3430 mPointerXMovementScale;
3431 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3432 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3433 mPointerYMovementScale;
3434
Prabir Pradhan1728b212021-10-19 16:00:03 -07003435 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003436 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3437
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003438 mPointerController->move(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003439 } else {
3440 mPointerVelocityControl.reset();
3441 }
3442
3443 down = isPointerDown(mCurrentRawState.buttonState);
3444 hovering = !down;
3445
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003446 float x, y;
3447 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003448 mPointerSimple.currentCoords.copyFrom(
3449 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3450 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3451 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3452 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3453 hovering ? 0.0f : 1.0f);
3454 mPointerSimple.currentProperties.id = 0;
3455 mPointerSimple.currentProperties.toolType =
3456 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3457 } else {
3458 mPointerVelocityControl.reset();
3459
3460 down = false;
3461 hovering = false;
3462 }
3463
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003464 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003465}
3466
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003467void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3468 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469
3470 mPointerVelocityControl.reset();
3471}
3472
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003473void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3474 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003475 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003476
3477 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003478 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003479 mPointerController->clearSpots();
3480 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003481 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003482 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003483 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003484 }
Garfield Tan9514d782020-11-10 16:37:23 -08003485 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003486
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003487 float xCursorPosition, yCursorPosition;
3488 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489
3490 if (mPointerSimple.down && !down) {
3491 mPointerSimple.down = false;
3492
3493 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003494 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3495 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003496 mLastRawState.buttonState, MotionClassification::NONE,
3497 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3498 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3499 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3500 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003501 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003502 }
3503
3504 if (mPointerSimple.hovering && !hovering) {
3505 mPointerSimple.hovering = false;
3506
3507 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003508 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3509 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3510 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003511 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3512 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3513 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3514 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003515 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003516 }
3517
3518 if (down) {
3519 if (!mPointerSimple.down) {
3520 mPointerSimple.down = true;
3521 mPointerSimple.downTime = when;
3522
3523 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003524 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003525 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3526 metaState, mCurrentRawState.buttonState,
3527 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3528 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3529 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3530 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003531 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003532 }
3533
3534 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003535 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3536 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003537 mCurrentRawState.buttonState, MotionClassification::NONE,
3538 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3539 &mPointerSimple.currentCoords, mOrientedXPrecision,
3540 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3541 mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003542 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003543 }
3544
3545 if (hovering) {
3546 if (!mPointerSimple.hovering) {
3547 mPointerSimple.hovering = true;
3548
3549 // Send hover enter.
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_HOVER_ENTER, 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 hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003561 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3562 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3563 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003564 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 (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3572 float vscroll = mCurrentRawState.rawVScroll;
3573 float hscroll = mCurrentRawState.rawHScroll;
3574 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3575 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3576
3577 // Send scroll.
3578 PointerCoords pointerCoords;
3579 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3580 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3581 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3582
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003583 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3584 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003585 mCurrentRawState.buttonState, MotionClassification::NONE,
3586 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3587 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3588 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3589 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003590 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003591 }
3592
3593 // Save state.
3594 if (down || hovering) {
3595 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3596 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3597 } else {
3598 mPointerSimple.reset();
3599 }
3600}
3601
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003602void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003603 mPointerSimple.currentCoords.clear();
3604 mPointerSimple.currentProperties.clear();
3605
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003606 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003607}
3608
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003609void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3610 uint32_t source, int32_t action, int32_t actionButton,
3611 int32_t flags, int32_t metaState, int32_t buttonState,
3612 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003613 const PointerCoords* coords, const uint32_t* idToIndex,
3614 BitSet32 idBits, int32_t changedId, float xPrecision,
3615 float yPrecision, nsecs_t downTime) {
3616 PointerCoords pointerCoords[MAX_POINTERS];
3617 PointerProperties pointerProperties[MAX_POINTERS];
3618 uint32_t pointerCount = 0;
3619 while (!idBits.isEmpty()) {
3620 uint32_t id = idBits.clearFirstMarkedBit();
3621 uint32_t index = idToIndex[id];
3622 pointerProperties[pointerCount].copyFrom(properties[index]);
3623 pointerCoords[pointerCount].copyFrom(coords[index]);
3624
3625 if (changedId >= 0 && id == uint32_t(changedId)) {
3626 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3627 }
3628
3629 pointerCount += 1;
3630 }
3631
3632 ALOG_ASSERT(pointerCount != 0);
3633
3634 if (changedId >= 0 && pointerCount == 1) {
3635 // Replace initial down and final up action.
3636 // We can compare the action without masking off the changed pointer index
3637 // because we know the index is 0.
3638 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3639 action = AMOTION_EVENT_ACTION_DOWN;
3640 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003641 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3642 action = AMOTION_EVENT_ACTION_CANCEL;
3643 } else {
3644 action = AMOTION_EVENT_ACTION_UP;
3645 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003646 } else {
3647 // Can't happen.
3648 ALOG_ASSERT(false);
3649 }
3650 }
3651 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3652 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003653 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003654 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003655 }
3656 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3657 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003658 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003659 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003660 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003661 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3662 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003663 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3664 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3665 downTime, std::move(frames));
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003666 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003667}
3668
3669bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3670 const PointerCoords* inCoords,
3671 const uint32_t* inIdToIndex,
3672 PointerProperties* outProperties,
3673 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3674 BitSet32 idBits) const {
3675 bool changed = false;
3676 while (!idBits.isEmpty()) {
3677 uint32_t id = idBits.clearFirstMarkedBit();
3678 uint32_t inIndex = inIdToIndex[id];
3679 uint32_t outIndex = outIdToIndex[id];
3680
3681 const PointerProperties& curInProperties = inProperties[inIndex];
3682 const PointerCoords& curInCoords = inCoords[inIndex];
3683 PointerProperties& curOutProperties = outProperties[outIndex];
3684 PointerCoords& curOutCoords = outCoords[outIndex];
3685
3686 if (curInProperties != curOutProperties) {
3687 curOutProperties.copyFrom(curInProperties);
3688 changed = true;
3689 }
3690
3691 if (curInCoords != curOutCoords) {
3692 curOutCoords.copyFrom(curInCoords);
3693 changed = true;
3694 }
3695 }
3696 return changed;
3697}
3698
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003699void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3700 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3701 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003702}
3703
Prabir Pradhan1728b212021-10-19 16:00:03 -07003704// Transform input device coordinates to display panel coordinates.
3705void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003706 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3707 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3708
arthurhunga36b28e2020-12-29 20:28:15 +08003709 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3710 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3711
Prabir Pradhan1728b212021-10-19 16:00:03 -07003712 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003713 // 0 - no swap and reverse.
3714 // 90 - swap x/y and reverse y.
3715 // 180 - reverse x, y.
3716 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003717 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003718 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003719 x = xScaled;
3720 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003721 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003722 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003723 y = xScaledMax;
3724 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003725 break;
3726 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003727 x = xScaledMax;
3728 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003729 break;
3730 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003731 y = xScaled;
3732 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003733 break;
3734 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003735 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003736 }
3737}
3738
Prabir Pradhan1728b212021-10-19 16:00:03 -07003739bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003740 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3741 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3742
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003743 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003744 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003745 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003746 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003747}
3748
3749const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3750 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003751 if (DEBUG_VIRTUAL_KEYS) {
3752 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3753 "left=%d, top=%d, right=%d, bottom=%d",
3754 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3755 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
3756 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003757
3758 if (virtualKey.isHit(x, y)) {
3759 return &virtualKey;
3760 }
3761 }
3762
3763 return nullptr;
3764}
3765
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003766void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3767 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3768 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003769
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003770 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003771
3772 if (currentPointerCount == 0) {
3773 // No pointers to assign.
3774 return;
3775 }
3776
3777 if (lastPointerCount == 0) {
3778 // All pointers are new.
3779 for (uint32_t i = 0; i < currentPointerCount; i++) {
3780 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003781 current.rawPointerData.pointers[i].id = id;
3782 current.rawPointerData.idToIndex[id] = i;
3783 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003784 }
3785 return;
3786 }
3787
3788 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003789 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003790 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003791 uint32_t id = last.rawPointerData.pointers[0].id;
3792 current.rawPointerData.pointers[0].id = id;
3793 current.rawPointerData.idToIndex[id] = 0;
3794 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003795 return;
3796 }
3797
3798 // General case.
3799 // We build a heap of squared euclidean distances between current and last pointers
3800 // associated with the current and last pointer indices. Then, we find the best
3801 // match (by distance) for each current pointer.
3802 // The pointers must have the same tool type but it is possible for them to
3803 // transition from hovering to touching or vice-versa while retaining the same id.
3804 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3805
3806 uint32_t heapSize = 0;
3807 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3808 currentPointerIndex++) {
3809 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3810 lastPointerIndex++) {
3811 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003812 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003813 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003814 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003815 if (currentPointer.toolType == lastPointer.toolType) {
3816 int64_t deltaX = currentPointer.x - lastPointer.x;
3817 int64_t deltaY = currentPointer.y - lastPointer.y;
3818
3819 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3820
3821 // Insert new element into the heap (sift up).
3822 heap[heapSize].currentPointerIndex = currentPointerIndex;
3823 heap[heapSize].lastPointerIndex = lastPointerIndex;
3824 heap[heapSize].distance = distance;
3825 heapSize += 1;
3826 }
3827 }
3828 }
3829
3830 // Heapify
3831 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3832 startIndex -= 1;
3833 for (uint32_t parentIndex = startIndex;;) {
3834 uint32_t childIndex = parentIndex * 2 + 1;
3835 if (childIndex >= heapSize) {
3836 break;
3837 }
3838
3839 if (childIndex + 1 < heapSize &&
3840 heap[childIndex + 1].distance < heap[childIndex].distance) {
3841 childIndex += 1;
3842 }
3843
3844 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3845 break;
3846 }
3847
3848 swap(heap[parentIndex], heap[childIndex]);
3849 parentIndex = childIndex;
3850 }
3851 }
3852
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003853 if (DEBUG_POINTER_ASSIGNMENT) {
3854 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3855 for (size_t i = 0; i < heapSize; i++) {
3856 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3857 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3858 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003859 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003860
3861 // Pull matches out by increasing order of distance.
3862 // To avoid reassigning pointers that have already been matched, the loop keeps track
3863 // of which last and current pointers have been matched using the matchedXXXBits variables.
3864 // It also tracks the used pointer id bits.
3865 BitSet32 matchedLastBits(0);
3866 BitSet32 matchedCurrentBits(0);
3867 BitSet32 usedIdBits(0);
3868 bool first = true;
3869 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3870 while (heapSize > 0) {
3871 if (first) {
3872 // The first time through the loop, we just consume the root element of
3873 // the heap (the one with smallest distance).
3874 first = false;
3875 } else {
3876 // Previous iterations consumed the root element of the heap.
3877 // Pop root element off of the heap (sift down).
3878 heap[0] = heap[heapSize];
3879 for (uint32_t parentIndex = 0;;) {
3880 uint32_t childIndex = parentIndex * 2 + 1;
3881 if (childIndex >= heapSize) {
3882 break;
3883 }
3884
3885 if (childIndex + 1 < heapSize &&
3886 heap[childIndex + 1].distance < heap[childIndex].distance) {
3887 childIndex += 1;
3888 }
3889
3890 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3891 break;
3892 }
3893
3894 swap(heap[parentIndex], heap[childIndex]);
3895 parentIndex = childIndex;
3896 }
3897
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003898 if (DEBUG_POINTER_ASSIGNMENT) {
3899 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3900 for (size_t j = 0; j < heapSize; j++) {
3901 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3902 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3903 heap[j].distance);
3904 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003905 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003906 }
3907
3908 heapSize -= 1;
3909
3910 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3911 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3912
3913 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3914 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3915
3916 matchedCurrentBits.markBit(currentPointerIndex);
3917 matchedLastBits.markBit(lastPointerIndex);
3918
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003919 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3920 current.rawPointerData.pointers[currentPointerIndex].id = id;
3921 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3922 current.rawPointerData.markIdBit(id,
3923 current.rawPointerData.isHovering(
3924 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003925 usedIdBits.markBit(id);
3926
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003927 if (DEBUG_POINTER_ASSIGNMENT) {
3928 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3929 ", distance=%" PRIu64,
3930 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3931 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003932 break;
3933 }
3934 }
3935
3936 // Assign fresh ids to pointers that were not matched in the process.
3937 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3938 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3939 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3940
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003941 current.rawPointerData.pointers[currentPointerIndex].id = id;
3942 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3943 current.rawPointerData.markIdBit(id,
3944 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003945
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003946 if (DEBUG_POINTER_ASSIGNMENT) {
3947 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
3948 id);
3949 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003950 }
3951}
3952
3953int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3954 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3955 return AKEY_STATE_VIRTUAL;
3956 }
3957
3958 for (const VirtualKey& virtualKey : mVirtualKeys) {
3959 if (virtualKey.keyCode == keyCode) {
3960 return AKEY_STATE_UP;
3961 }
3962 }
3963
3964 return AKEY_STATE_UNKNOWN;
3965}
3966
3967int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3968 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3969 return AKEY_STATE_VIRTUAL;
3970 }
3971
3972 for (const VirtualKey& virtualKey : mVirtualKeys) {
3973 if (virtualKey.scanCode == scanCode) {
3974 return AKEY_STATE_UP;
3975 }
3976 }
3977
3978 return AKEY_STATE_UNKNOWN;
3979}
3980
3981bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3982 const int32_t* keyCodes, uint8_t* outFlags) {
3983 for (const VirtualKey& virtualKey : mVirtualKeys) {
3984 for (size_t i = 0; i < numCodes; i++) {
3985 if (virtualKey.keyCode == keyCodes[i]) {
3986 outFlags[i] = 1;
3987 }
3988 }
3989 }
3990
3991 return true;
3992}
3993
3994std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3995 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003996 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003997 return std::make_optional(mPointerController->getDisplayId());
3998 } else {
3999 return std::make_optional(mViewport.displayId);
4000 }
4001 }
4002 return std::nullopt;
4003}
4004
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004005} // namespace android