blob: d17cdf55590c67076cde40e5fe87f56a3268833b [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
HQ Liue6983c72022-04-19 22:14:56 +000045// Minimum width between two pointers to determine a gesture as freeform gesture in mm
46static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070047// --- Static Definitions ---
48
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000049static const DisplayViewport kUninitializedViewport;
50
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070051template <typename T>
52inline static void swap(T& a, T& b) {
53 T temp = a;
54 a = b;
55 b = temp;
56}
57
58static float calculateCommonVector(float a, float b) {
59 if (a > 0 && b > 0) {
60 return a < b ? a : b;
61 } else if (a < 0 && b < 0) {
62 return a > b ? a : b;
63 } else {
64 return 0;
65 }
66}
67
68inline static float distance(float x1, float y1, float x2, float y2) {
69 return hypotf(x1 - x2, y1 - y2);
70}
71
72inline static int32_t signExtendNybble(int32_t value) {
73 return value >= 8 ? value - 16 : value;
74}
75
76// --- RawPointerAxes ---
77
78RawPointerAxes::RawPointerAxes() {
79 clear();
80}
81
82void RawPointerAxes::clear() {
83 x.clear();
84 y.clear();
85 pressure.clear();
86 touchMajor.clear();
87 touchMinor.clear();
88 toolMajor.clear();
89 toolMinor.clear();
90 orientation.clear();
91 distance.clear();
92 tiltX.clear();
93 tiltY.clear();
94 trackingId.clear();
95 slot.clear();
96}
97
98// --- RawPointerData ---
99
100RawPointerData::RawPointerData() {
101 clear();
102}
103
104void RawPointerData::clear() {
105 pointerCount = 0;
106 clearIdBits();
107}
108
109void RawPointerData::copyFrom(const RawPointerData& other) {
110 pointerCount = other.pointerCount;
111 hoveringIdBits = other.hoveringIdBits;
112 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800113 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700114
115 for (uint32_t i = 0; i < pointerCount; i++) {
116 pointers[i] = other.pointers[i];
117
118 int id = pointers[i].id;
119 idToIndex[id] = other.idToIndex[id];
120 }
121}
122
123void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
124 float x = 0, y = 0;
125 uint32_t count = touchingIdBits.count();
126 if (count) {
127 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
128 uint32_t id = idBits.clearFirstMarkedBit();
129 const Pointer& pointer = pointerForId(id);
130 x += pointer.x;
131 y += pointer.y;
132 }
133 x /= count;
134 y /= count;
135 }
136 *outX = x;
137 *outY = y;
138}
139
140// --- CookedPointerData ---
141
142CookedPointerData::CookedPointerData() {
143 clear();
144}
145
146void CookedPointerData::clear() {
147 pointerCount = 0;
148 hoveringIdBits.clear();
149 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800150 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000151 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700152}
153
154void CookedPointerData::copyFrom(const CookedPointerData& other) {
155 pointerCount = other.pointerCount;
156 hoveringIdBits = other.hoveringIdBits;
157 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000158 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700159
160 for (uint32_t i = 0; i < pointerCount; i++) {
161 pointerProperties[i].copyFrom(other.pointerProperties[i]);
162 pointerCoords[i].copyFrom(other.pointerCoords[i]);
163
164 int id = pointerProperties[i].id;
165 idToIndex[id] = other.idToIndex[id];
166 }
167}
168
169// --- TouchInputMapper ---
170
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800171TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
172 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000173 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700174 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100175 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700176 mDisplayWidth(-1),
177 mDisplayHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700178 mPhysicalWidth(-1),
179 mPhysicalHeight(-1),
180 mPhysicalLeft(0),
181 mPhysicalTop(0),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700182 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700183
184TouchInputMapper::~TouchInputMapper() {}
185
Philip Junker4af3b3d2021-12-14 10:36:55 +0100186uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700187 return mSource;
188}
189
190void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
191 InputMapper::populateDeviceInfo(info);
192
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000193 if (mDeviceMode == DeviceMode::DISABLED) {
194 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700195 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000196
197 info->addMotionRange(mOrientedRanges.x);
198 info->addMotionRange(mOrientedRanges.y);
199 info->addMotionRange(mOrientedRanges.pressure);
200
201 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
202 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
203 //
204 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
205 // motion, i.e. the hardware dimensions, as the finger could move completely across the
206 // touchpad in one sample cycle.
207 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
208 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
209 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
210 x.resolution);
211 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
212 y.resolution);
213 }
214
215 if (mOrientedRanges.size) {
216 info->addMotionRange(*mOrientedRanges.size);
217 }
218
219 if (mOrientedRanges.touchMajor) {
220 info->addMotionRange(*mOrientedRanges.touchMajor);
221 info->addMotionRange(*mOrientedRanges.touchMinor);
222 }
223
224 if (mOrientedRanges.toolMajor) {
225 info->addMotionRange(*mOrientedRanges.toolMajor);
226 info->addMotionRange(*mOrientedRanges.toolMinor);
227 }
228
229 if (mOrientedRanges.orientation) {
230 info->addMotionRange(*mOrientedRanges.orientation);
231 }
232
233 if (mOrientedRanges.distance) {
234 info->addMotionRange(*mOrientedRanges.distance);
235 }
236
237 if (mOrientedRanges.tilt) {
238 info->addMotionRange(*mOrientedRanges.tilt);
239 }
240
241 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
242 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
243 }
244 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
245 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
246 }
247 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
248 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
249 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
250 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
251 x.resolution);
252 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
253 y.resolution);
254 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
255 x.resolution);
256 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
257 y.resolution);
258 }
259 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000260 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700261}
262
263void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700264 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800265 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700266 dumpParameters(dump);
267 dumpVirtualKeys(dump);
268 dumpRawPointerAxes(dump);
269 dumpCalibration(dump);
270 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700271 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700272
273 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700274 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
275 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
276 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
277 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
278 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
279 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
280 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
281 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
282 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
283 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
284 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
285 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
286 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
287 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
288
289 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
290 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
291 mLastRawState.rawPointerData.pointerCount);
292 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
293 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
294 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
295 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
296 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
297 "toolType=%d, isHovering=%s\n",
298 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
299 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
300 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
301 pointer.distance, pointer.toolType, toString(pointer.isHovering));
302 }
303
304 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
305 mLastCookedState.buttonState);
306 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
307 mLastCookedState.cookedPointerData.pointerCount);
308 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
309 const PointerProperties& pointerProperties =
310 mLastCookedState.cookedPointerData.pointerProperties[i];
311 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000312 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
313 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
314 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700315 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
316 "toolType=%d, isHovering=%s\n",
317 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
327 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
328 pointerProperties.toolType,
329 toString(mLastCookedState.cookedPointerData.isHovering(i)));
330 }
331
332 dump += INDENT3 "Stylus Fusion:\n";
333 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
334 toString(mExternalStylusConnected));
335 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
336 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
337 mExternalStylusFusionTimeout);
338 dump += INDENT3 "External Stylus State:\n";
339 dumpStylusState(dump, mExternalStylusState);
340
Michael Wright227c5542020-07-02 18:30:52 +0100341 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700342 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
343 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
344 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
345 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
346 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
347 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
348 }
349}
350
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700351std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
352 const InputReaderConfiguration* config,
353 uint32_t changes) {
354 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355
356 mConfig = *config;
357
358 if (!changes) { // first time only
359 // Configure basic parameters.
360 configureParameters();
361
362 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800363 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000364 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700365
366 // Configure absolute axis information.
367 configureRawPointerAxes();
368
369 // Prepare input device calibration.
370 parseCalibration();
371 resolveCalibration();
372 }
373
374 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
375 // Update location calibration to reflect current settings
376 updateAffineTransformation();
377 }
378
379 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
380 // Update pointer speed.
381 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
382 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
383 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
384 }
385
386 bool resetNeeded = false;
387 if (!changes ||
388 (changes &
389 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800390 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700391 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
392 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
393 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700394 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700395 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700396 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700397 }
398
399 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700400 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000401
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 // Send reset, unless this is the first time the device has been configured,
403 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000404 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700405 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700406 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700407}
408
409void TouchInputMapper::resolveExternalStylusPresence() {
410 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800411 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700412 mExternalStylusConnected = !devices.empty();
413
414 if (!mExternalStylusConnected) {
415 resetExternalStylus();
416 }
417}
418
419void TouchInputMapper::configureParameters() {
420 // Use the pointer presentation mode for devices that do not support distinct
421 // multitouch. The spot-based presentation relies on being able to accurately
422 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800423 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100424 ? Parameters::GestureMode::SINGLE_TOUCH
425 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700427 std::string gestureModeString;
428 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800429 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700430 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100431 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700432 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100433 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700434 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700435 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436 }
437 }
438
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800439 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700440 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100441 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800442 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100444 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700445 } else {
446 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100447 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448 }
449
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800450 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700451
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700452 std::string deviceTypeString;
453 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100456 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100458 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100460 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700461 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700462 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463 }
464 }
465
Michael Wright227c5542020-07-02 18:30:52 +0100466 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700467 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800468 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700469
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700470 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700471 std::string orientationString;
472 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700473 orientationString)) {
474 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
475 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
476 } else if (orientationString == "ORIENTATION_90") {
477 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
478 } else if (orientationString == "ORIENTATION_180") {
479 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
480 } else if (orientationString == "ORIENTATION_270") {
481 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
482 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700483 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700484 }
485 }
486
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700487 mParameters.hasAssociatedDisplay = false;
488 mParameters.associatedDisplayIsExternal = false;
489 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100490 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
491 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700492 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100493 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700495 std::string uniqueDisplayId;
496 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800497 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700498 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
499 }
500 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800501 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502 mParameters.hasAssociatedDisplay = true;
503 }
504
505 // Initial downs on external touch devices should wake the device.
506 // Normally we don't do this for internal touch screens to prevent them from waking
507 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800508 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700509 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000510
511 mParameters.supportsUsi = false;
512 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
513 mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514}
515
516void TouchInputMapper::dumpParameters(std::string& dump) {
517 dump += INDENT3 "Parameters:\n";
518
Dominik Laskowski75788452021-02-09 18:51:25 -0800519 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700520
Dominik Laskowski75788452021-02-09 18:51:25 -0800521 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700522
523 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
524 "displayId='%s'\n",
525 toString(mParameters.hasAssociatedDisplay),
526 toString(mParameters.associatedDisplayIsExternal),
527 mParameters.uniqueDisplayId.c_str());
528 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800529 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000530 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700531}
532
533void TouchInputMapper::configureRawPointerAxes() {
534 mRawPointerAxes.clear();
535}
536
537void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
538 dump += INDENT3 "Raw Touch Axes:\n";
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
549 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
550 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
551 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
552}
553
554bool TouchInputMapper::hasExternalStylus() const {
555 return mExternalStylusConnected;
556}
557
558/**
559 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000560 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800561 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000562 * 3. Get the matching viewport by either unique id in idc file or by the display type
563 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800564 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700565 */
566std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800567 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000568 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800569 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700570 }
571
Christine Franks2a2293c2022-01-18 11:51:16 -0800572 const std::optional<std::string> associatedDisplayUniqueId =
573 getDeviceContext().getAssociatedDisplayUniqueId();
574 if (associatedDisplayUniqueId) {
575 return getDeviceContext().getAssociatedViewport();
576 }
577
Michael Wright227c5542020-07-02 18:30:52 +0100578 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800579 std::optional<DisplayViewport> viewport =
580 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
581 if (viewport) {
582 return viewport;
583 } else {
584 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
585 mConfig.defaultPointerDisplayId);
586 }
587 }
588
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700589 // Check if uniqueDisplayId is specified in idc file.
590 if (!mParameters.uniqueDisplayId.empty()) {
591 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
592 }
593
594 ViewportType viewportTypeToUse;
595 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100596 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700597 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100598 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700599 }
600
601 std::optional<DisplayViewport> viewport =
602 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100603 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700604 ALOGW("Input device %s should be associated with external display, "
605 "fallback to internal one for the external viewport is not found.",
606 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100607 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700608 }
609
610 return viewport;
611 }
612
613 // No associated display, return a non-display viewport.
614 DisplayViewport newViewport;
615 // Raw width and height in the natural orientation.
616 int32_t rawWidth = mRawPointerAxes.getRawWidth();
617 int32_t rawHeight = mRawPointerAxes.getRawHeight();
618 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
619 return std::make_optional(newViewport);
620}
621
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800622int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
623 if (resolution < 0) {
624 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
625 getDeviceName().c_str());
626 return 0;
627 }
628 return resolution;
629}
630
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800631void TouchInputMapper::initializeSizeRanges() {
632 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
633 mSizeScale = 0.0f;
634 return;
635 }
636
637 // Size of diagonal axis.
638 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
639
640 // Size factors.
641 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
642 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
643 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
644 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
645 } else {
646 mSizeScale = 0.0f;
647 }
648
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700649 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
650 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
651 .source = mSource,
652 .min = 0,
653 .max = diagonalSize,
654 .flat = 0,
655 .fuzz = 0,
656 .resolution = 0,
657 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800658
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800659 if (mRawPointerAxes.touchMajor.valid) {
660 mRawPointerAxes.touchMajor.resolution =
661 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700662 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800663 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800664
665 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700666 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800667 if (mRawPointerAxes.touchMinor.valid) {
668 mRawPointerAxes.touchMinor.resolution =
669 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700670 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800671 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800672
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700673 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
674 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
675 .source = mSource,
676 .min = 0,
677 .max = diagonalSize,
678 .flat = 0,
679 .fuzz = 0,
680 .resolution = 0,
681 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800682 if (mRawPointerAxes.toolMajor.valid) {
683 mRawPointerAxes.toolMajor.resolution =
684 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700685 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800686 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800687
688 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700689 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800690 if (mRawPointerAxes.toolMinor.valid) {
691 mRawPointerAxes.toolMinor.resolution =
692 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700693 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800694 }
695
696 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700697 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
698 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
699 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
700 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800701 } else {
702 // Support for other calibrations can be added here.
703 ALOGW("%s calibration is not supported for size ranges at the moment. "
704 "Using raw resolution instead",
705 ftl::enum_string(mCalibration.sizeCalibration).c_str());
706 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800707
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700708 mOrientedRanges.size = InputDeviceInfo::MotionRange{
709 .axis = AMOTION_EVENT_AXIS_SIZE,
710 .source = mSource,
711 .min = 0,
712 .max = 1.0,
713 .flat = 0,
714 .fuzz = 0,
715 .resolution = 0,
716 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800717}
718
719void TouchInputMapper::initializeOrientedRanges() {
720 // Configure X and Y factors.
721 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
722 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
723 mXPrecision = 1.0f / mXScale;
724 mYPrecision = 1.0f / mYScale;
725
726 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
727 mOrientedRanges.x.source = mSource;
728 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
729 mOrientedRanges.y.source = mSource;
730
731 // Scale factor for terms that are not oriented in a particular axis.
732 // If the pixels are square then xScale == yScale otherwise we fake it
733 // by choosing an average.
734 mGeometricScale = avg(mXScale, mYScale);
735
736 initializeSizeRanges();
737
738 // Pressure factors.
739 mPressureScale = 0;
740 float pressureMax = 1.0;
741 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
742 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700743 if (mCalibration.pressureScale) {
744 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800745 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
746 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
747 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
748 }
749 }
750
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700751 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
752 .axis = AMOTION_EVENT_AXIS_PRESSURE,
753 .source = mSource,
754 .min = 0,
755 .max = pressureMax,
756 .flat = 0,
757 .fuzz = 0,
758 .resolution = 0,
759 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800760
761 // Tilt
762 mTiltXCenter = 0;
763 mTiltXScale = 0;
764 mTiltYCenter = 0;
765 mTiltYScale = 0;
766 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
767 if (mHaveTilt) {
768 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
769 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
770 mTiltXScale = M_PI / 180;
771 mTiltYScale = M_PI / 180;
772
773 if (mRawPointerAxes.tiltX.resolution) {
774 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
775 }
776 if (mRawPointerAxes.tiltY.resolution) {
777 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
778 }
779
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700780 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
781 .axis = AMOTION_EVENT_AXIS_TILT,
782 .source = mSource,
783 .min = 0,
784 .max = M_PI_2,
785 .flat = 0,
786 .fuzz = 0,
787 .resolution = 0,
788 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800789 }
790
791 // Orientation
792 mOrientationScale = 0;
793 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700794 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
795 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
796 .source = mSource,
797 .min = -M_PI,
798 .max = M_PI,
799 .flat = 0,
800 .fuzz = 0,
801 .resolution = 0,
802 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800803
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800804 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
805 if (mCalibration.orientationCalibration ==
806 Calibration::OrientationCalibration::INTERPOLATED) {
807 if (mRawPointerAxes.orientation.valid) {
808 if (mRawPointerAxes.orientation.maxValue > 0) {
809 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
810 } else if (mRawPointerAxes.orientation.minValue < 0) {
811 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
812 } else {
813 mOrientationScale = 0;
814 }
815 }
816 }
817
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700818 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
819 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
820 .source = mSource,
821 .min = -M_PI_2,
822 .max = M_PI_2,
823 .flat = 0,
824 .fuzz = 0,
825 .resolution = 0,
826 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800827 }
828
829 // Distance
830 mDistanceScale = 0;
831 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
832 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700833 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800834 }
835
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700836 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800837
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700838 .axis = AMOTION_EVENT_AXIS_DISTANCE,
839 .source = mSource,
840 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
841 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
842 .flat = 0,
843 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
844 .resolution = 0,
845 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800846 }
847
848 // Compute oriented precision, scales and ranges.
849 // Note that the maximum value reported is an inclusive maximum value so it is one
850 // unit less than the total width or height of the display.
851 switch (mInputDeviceOrientation) {
852 case DISPLAY_ORIENTATION_90:
853 case DISPLAY_ORIENTATION_270:
854 mOrientedXPrecision = mYPrecision;
855 mOrientedYPrecision = mXPrecision;
856
857 mOrientedRanges.x.min = 0;
858 mOrientedRanges.x.max = mDisplayHeight - 1;
859 mOrientedRanges.x.flat = 0;
860 mOrientedRanges.x.fuzz = 0;
861 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
862
863 mOrientedRanges.y.min = 0;
864 mOrientedRanges.y.max = mDisplayWidth - 1;
865 mOrientedRanges.y.flat = 0;
866 mOrientedRanges.y.fuzz = 0;
867 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
868 break;
869
870 default:
871 mOrientedXPrecision = mXPrecision;
872 mOrientedYPrecision = mYPrecision;
873
874 mOrientedRanges.x.min = 0;
875 mOrientedRanges.x.max = mDisplayWidth - 1;
876 mOrientedRanges.x.flat = 0;
877 mOrientedRanges.x.fuzz = 0;
878 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
879
880 mOrientedRanges.y.min = 0;
881 mOrientedRanges.y.max = mDisplayHeight - 1;
882 mOrientedRanges.y.flat = 0;
883 mOrientedRanges.y.fuzz = 0;
884 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
885 break;
886 }
887}
888
Prabir Pradhan1728b212021-10-19 16:00:03 -0700889void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000890 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700891
892 resolveExternalStylusPresence();
893
894 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100895 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000896 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700897 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100898 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700899 if (hasStylus()) {
900 mSource |= AINPUT_SOURCE_STYLUS;
901 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800902 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100904 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700905 if (hasStylus()) {
906 mSource |= AINPUT_SOURCE_STYLUS;
907 }
908 if (hasExternalStylus()) {
909 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
910 }
Michael Wright227c5542020-07-02 18:30:52 +0100911 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700912 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100913 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700914 } else {
915 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100916 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700917 }
918
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000919 const std::optional<DisplayViewport> newViewportOpt = findViewport();
920
921 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700922 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
923 ALOGW("Touch device '%s' did not report support for X or Y axis! "
924 "The device will be inoperable.",
925 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100926 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000927 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700928 ALOGI("Touch device '%s' could not query the properties of its associated "
929 "display. The device will be inoperable until the display size "
930 "becomes available.",
931 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100932 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000933 } else if (!newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000934 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
935 getDeviceName().c_str(), getDeviceId());
936 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000937 }
938
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700939 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700940 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
941 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000942 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
943 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
944 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
945 const float rawMeanResolution =
946 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700947
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000948 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
949 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700950 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700951 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000952 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
953 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
954 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700955
Michael Wright227c5542020-07-02 18:30:52 +0100956 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700957 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700958 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
959 int32_t naturalPhysicalLeft, naturalPhysicalTop;
960 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700961
Prabir Pradhan1728b212021-10-19 16:00:03 -0700962 // Apply the inverse of the input device orientation so that the input device is
963 // configured in the same orientation as the viewport. The input device orientation will
964 // be re-applied by mInputDeviceOrientation.
965 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700966 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700967 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700968 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700969 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
970 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800971 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700972 naturalPhysicalTop = mViewport.physicalLeft;
973 naturalDeviceWidth = mViewport.deviceHeight;
974 naturalDeviceHeight = mViewport.deviceWidth;
975 break;
976 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
978 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
979 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
980 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
981 naturalDeviceWidth = mViewport.deviceWidth;
982 naturalDeviceHeight = mViewport.deviceHeight;
983 break;
984 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700985 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
986 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
987 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800988 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700989 naturalDeviceWidth = mViewport.deviceHeight;
990 naturalDeviceHeight = mViewport.deviceWidth;
991 break;
992 case DISPLAY_ORIENTATION_0:
993 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
995 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
996 naturalPhysicalLeft = mViewport.physicalLeft;
997 naturalPhysicalTop = mViewport.physicalTop;
998 naturalDeviceWidth = mViewport.deviceWidth;
999 naturalDeviceHeight = mViewport.deviceHeight;
1000 break;
1001 }
1002
1003 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
1004 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
1005 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
1006 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
1007 }
1008
1009 mPhysicalWidth = naturalPhysicalWidth;
1010 mPhysicalHeight = naturalPhysicalHeight;
1011 mPhysicalLeft = naturalPhysicalLeft;
1012 mPhysicalTop = naturalPhysicalTop;
1013
Prabir Pradhan1728b212021-10-19 16:00:03 -07001014 const int32_t oldDisplayWidth = mDisplayWidth;
1015 const int32_t oldDisplayHeight = mDisplayHeight;
1016 mDisplayWidth = naturalDeviceWidth;
1017 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -07001018
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001019 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1020 // anything if the device is already orientation-aware. If the device is not
1021 // orientation-aware, then we need to apply the inverse rotation of the display so that
1022 // when the display rotation is applied later as a part of the per-window transform, we
1023 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001024 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001025 ? DISPLAY_ORIENTATION_0
1026 : getInverseRotation(mViewport.orientation);
1027 // For orientation-aware devices that work in the un-rotated coordinate space, the
1028 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001029 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
1030 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
1031 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001032
1033 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001034 mInputDeviceOrientation =
1035 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001036 } else {
1037 mPhysicalWidth = rawWidth;
1038 mPhysicalHeight = rawHeight;
1039 mPhysicalLeft = 0;
1040 mPhysicalTop = 0;
1041
Prabir Pradhan1728b212021-10-19 16:00:03 -07001042 mDisplayWidth = rawWidth;
1043 mDisplayHeight = rawHeight;
1044 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001045 }
1046 }
1047
1048 // If moving between pointer modes, need to reset some state.
1049 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1050 if (deviceModeChanged) {
1051 mOrientedRanges.clear();
1052 }
1053
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001054 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
1055 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +01001056 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001057 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001058 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1059 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001060 if (mPointerController == nullptr) {
1061 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001063 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001064 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1065 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066 } else {
lilinnandef700b2022-06-17 19:32:01 +08001067 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1068 !mConfig.showTouches) {
1069 mPointerController->clearSpots();
1070 }
Michael Wright17db18e2020-06-26 20:51:44 +01001071 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001072 }
1073
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001074 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001075 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1076 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001077 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1078 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001079
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001080 configureVirtualKeys();
1081
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001082 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001083
1084 // Location
1085 updateAffineTransformation();
1086
Michael Wright227c5542020-07-02 18:30:52 +01001087 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001088 // Compute pointer gesture detection parameters.
1089 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001090 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091
1092 // Scale movements such that one whole swipe of the touch pad covers a
1093 // given area relative to the diagonal size of the display when no acceleration
1094 // is applied.
1095 // Assume that the touch pad has a square aspect ratio such that movements in
1096 // X and Y of the same number of raw units cover the same physical distance.
1097 mPointerXMovementScale =
1098 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1099 mPointerYMovementScale = mPointerXMovementScale;
1100
1101 // Scale zooms to cover a smaller range of the display than movements do.
1102 // This value determines the area around the pointer that is affected by freeform
1103 // pointer gestures.
1104 mPointerXZoomScale =
1105 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1106 mPointerYZoomScale = mPointerXZoomScale;
1107
HQ Liue6983c72022-04-19 22:14:56 +00001108 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1109 // axis is non positive value.
1110 const float minFreeformGestureWidth =
1111 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1112
1113 mPointerGestureMaxSwipeWidth =
1114 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1115 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 }
1117
1118 // Inform the dispatcher about the changes.
1119 *outResetNeeded = true;
1120 bumpGeneration();
1121 }
1122}
1123
Prabir Pradhan1728b212021-10-19 16:00:03 -07001124void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001125 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001126 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1127 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1129 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1130 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1131 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001132 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133}
1134
1135void TouchInputMapper::configureVirtualKeys() {
1136 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001137 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138
1139 mVirtualKeys.clear();
1140
1141 if (virtualKeyDefinitions.size() == 0) {
1142 return;
1143 }
1144
1145 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1146 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1147 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1148 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1149
1150 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1151 VirtualKey virtualKey;
1152
1153 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1154 int32_t keyCode;
1155 int32_t dummyKeyMetaState;
1156 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001157 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1158 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1160 continue; // drop the key
1161 }
1162
1163 virtualKey.keyCode = keyCode;
1164 virtualKey.flags = flags;
1165
1166 // convert the key definition's display coordinates into touch coordinates for a hit box
1167 int32_t halfWidth = virtualKeyDefinition.width / 2;
1168 int32_t halfHeight = virtualKeyDefinition.height / 2;
1169
1170 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001171 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 touchScreenLeft;
1173 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001174 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001176 virtualKey.hitTop =
1177 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001179 virtualKey.hitBottom =
1180 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 touchScreenTop;
1182 mVirtualKeys.push_back(virtualKey);
1183 }
1184}
1185
1186void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1187 if (!mVirtualKeys.empty()) {
1188 dump += INDENT3 "Virtual Keys:\n";
1189
1190 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1191 const VirtualKey& virtualKey = mVirtualKeys[i];
1192 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1193 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1194 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1195 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1196 }
1197 }
1198}
1199
1200void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001201 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 Calibration& out = mCalibration;
1203
1204 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001206 std::string sizeCalibrationString;
1207 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001215 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001218 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001219 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 }
1221 }
1222
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001223 float sizeScale;
1224
1225 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1226 out.sizeScale = sizeScale;
1227 }
1228 float sizeBias;
1229 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1230 out.sizeBias = sizeBias;
1231 }
1232 bool sizeIsSummed;
1233 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1234 out.sizeIsSummed = sizeIsSummed;
1235 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236
1237 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001238 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001239 std::string pressureCalibrationString;
1240 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001242 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001244 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001246 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 } else if (pressureCalibrationString != "default") {
1248 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001249 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251 }
1252
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001253 float pressureScale;
1254 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1255 out.pressureScale = pressureScale;
1256 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257
1258 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001259 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001260 std::string orientationCalibrationString;
1261 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001263 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001265 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001267 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 } else if (orientationCalibrationString != "default") {
1269 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001270 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272 }
1273
1274 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001275 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001276 std::string distanceCalibrationString;
1277 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001279 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001281 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 } else if (distanceCalibrationString != "default") {
1283 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001284 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 }
1286 }
1287
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001288 float distanceScale;
1289 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1290 out.distanceScale = distanceScale;
1291 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292
Michael Wright227c5542020-07-02 18:30:52 +01001293 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001294 std::string coverageCalibrationString;
1295 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001297 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001299 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 } else if (coverageCalibrationString != "default") {
1301 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001302 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 }
1304 }
1305}
1306
1307void TouchInputMapper::resolveCalibration() {
1308 // Size
1309 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001310 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1311 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 }
1313 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001314 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 }
1316
1317 // Pressure
1318 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001319 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1320 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001321 }
1322 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001323 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 }
1325
1326 // Orientation
1327 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001328 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1329 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 }
1331 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001332 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333 }
1334
1335 // Distance
1336 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001337 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1338 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001339 }
1340 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001341 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001342 }
1343
1344 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001345 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1346 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001347 }
1348}
1349
1350void TouchInputMapper::dumpCalibration(std::string& dump) {
1351 dump += INDENT3 "Calibration:\n";
1352
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001353 dump += INDENT4 "touch.size.calibration: ";
1354 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001355
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001356 if (mCalibration.sizeScale) {
1357 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001358 }
1359
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001360 if (mCalibration.sizeBias) {
1361 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001362 }
1363
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001364 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001365 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001366 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001367 }
1368
1369 // Pressure
1370 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001371 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001372 dump += INDENT4 "touch.pressure.calibration: none\n";
1373 break;
Michael Wright227c5542020-07-02 18:30:52 +01001374 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001375 dump += INDENT4 "touch.pressure.calibration: physical\n";
1376 break;
Michael Wright227c5542020-07-02 18:30:52 +01001377 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1379 break;
1380 default:
1381 ALOG_ASSERT(false);
1382 }
1383
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001384 if (mCalibration.pressureScale) {
1385 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386 }
1387
1388 // Orientation
1389 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001390 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391 dump += INDENT4 "touch.orientation.calibration: none\n";
1392 break;
Michael Wright227c5542020-07-02 18:30:52 +01001393 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001394 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1395 break;
Michael Wright227c5542020-07-02 18:30:52 +01001396 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001397 dump += INDENT4 "touch.orientation.calibration: vector\n";
1398 break;
1399 default:
1400 ALOG_ASSERT(false);
1401 }
1402
1403 // Distance
1404 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001405 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001406 dump += INDENT4 "touch.distance.calibration: none\n";
1407 break;
Michael Wright227c5542020-07-02 18:30:52 +01001408 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001409 dump += INDENT4 "touch.distance.calibration: scaled\n";
1410 break;
1411 default:
1412 ALOG_ASSERT(false);
1413 }
1414
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001415 if (mCalibration.distanceScale) {
1416 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001417 }
1418
1419 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001420 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001421 dump += INDENT4 "touch.coverage.calibration: none\n";
1422 break;
Michael Wright227c5542020-07-02 18:30:52 +01001423 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001424 dump += INDENT4 "touch.coverage.calibration: box\n";
1425 break;
1426 default:
1427 ALOG_ASSERT(false);
1428 }
1429}
1430
1431void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1432 dump += INDENT3 "Affine Transformation:\n";
1433
1434 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1435 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1436 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1437 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1438 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1439 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1440}
1441
1442void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001443 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001444 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001445}
1446
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001447std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001448 std::list<NotifyArgs> out = cancelTouch(when, when);
1449 updateTouchSpots();
1450
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001451 mCursorButtonAccumulator.reset(getDeviceContext());
1452 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001453 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001454
1455 mPointerVelocityControl.reset();
1456 mWheelXVelocityControl.reset();
1457 mWheelYVelocityControl.reset();
1458
1459 mRawStatesPending.clear();
1460 mCurrentRawState.clear();
1461 mCurrentCookedState.clear();
1462 mLastRawState.clear();
1463 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001464 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001465 mSentHoverEnter = false;
1466 mHavePointerIds = false;
1467 mCurrentMotionAborted = false;
1468 mDownTime = 0;
1469
1470 mCurrentVirtualKey.down = false;
1471
1472 mPointerGesture.reset();
1473 mPointerSimple.reset();
1474 resetExternalStylus();
1475
1476 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001477 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001478 mPointerController->clearSpots();
1479 }
1480
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001481 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001482}
1483
1484void TouchInputMapper::resetExternalStylus() {
1485 mExternalStylusState.clear();
1486 mExternalStylusId = -1;
1487 mExternalStylusFusionTimeout = LLONG_MAX;
1488 mExternalStylusDataPending = false;
1489}
1490
1491void TouchInputMapper::clearStylusDataPendingFlags() {
1492 mExternalStylusDataPending = false;
1493 mExternalStylusFusionTimeout = LLONG_MAX;
1494}
1495
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001496std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001497 mCursorButtonAccumulator.process(rawEvent);
1498 mCursorScrollAccumulator.process(rawEvent);
1499 mTouchButtonAccumulator.process(rawEvent);
1500
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001501 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001502 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001503 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001504 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001505 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001506}
1507
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001508std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1509 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001510 if (mDeviceMode == DeviceMode::DISABLED) {
1511 // Only save the last pending state when the device is disabled.
1512 mRawStatesPending.clear();
1513 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001514 // Push a new state.
1515 mRawStatesPending.emplace_back();
1516
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001517 RawState& next = mRawStatesPending.back();
1518 next.clear();
1519 next.when = when;
1520 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521
1522 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001523 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1525
1526 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001527 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1528 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001529 mCursorScrollAccumulator.finishSync();
1530
1531 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001532 syncTouch(when, &next);
1533
1534 // The last RawState is the actually second to last, since we just added a new state
1535 const RawState& last =
1536 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001537
1538 // Assign pointer ids.
1539 if (!mHavePointerIds) {
1540 assignPointerIds(last, next);
1541 }
1542
Harry Cutts45483602022-08-24 14:36:48 +00001543 ALOGD_IF(DEBUG_RAW_EVENTS,
1544 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1545 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1546 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1547 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1548 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1549 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550
Arthur Hung9ad18942021-06-19 02:04:46 +00001551 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1552 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1553 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1554 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1555 next.rawPointerData.hoveringIdBits.value);
1556 }
1557
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001558 out += processRawTouches(false /*timeout*/);
1559 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001560}
1561
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001562std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1563 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001564 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001565 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001566 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001567 }
1568
1569 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1570 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1571 // touching the current state will only observe the events that have been dispatched to the
1572 // rest of the pipeline.
1573 const size_t N = mRawStatesPending.size();
1574 size_t count;
1575 for (count = 0; count < N; count++) {
1576 const RawState& next = mRawStatesPending[count];
1577
1578 // A failure to assign the stylus id means that we're waiting on stylus data
1579 // and so should defer the rest of the pipeline.
1580 if (assignExternalStylusId(next, timeout)) {
1581 break;
1582 }
1583
1584 // All ready to go.
1585 clearStylusDataPendingFlags();
1586 mCurrentRawState.copyFrom(next);
1587 if (mCurrentRawState.when < mLastRawState.when) {
1588 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001589 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001591 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592 }
1593 if (count != 0) {
1594 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1595 }
1596
1597 if (mExternalStylusDataPending) {
1598 if (timeout) {
1599 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1600 clearStylusDataPendingFlags();
1601 mCurrentRawState.copyFrom(mLastRawState);
Harry Cutts45483602022-08-24 14:36:48 +00001602 ALOGD_IF(DEBUG_STYLUS_FUSION,
1603 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001604 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001605 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1607 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1608 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1609 }
1610 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001611 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001612}
1613
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001614std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1615 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 // Always start with a clean state.
1617 mCurrentCookedState.clear();
1618
1619 // Apply stylus buttons to current raw state.
1620 applyExternalStylusButtonState(when);
1621
1622 // Handle policy on initial down or hover events.
1623 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1624 mCurrentRawState.rawPointerData.pointerCount != 0;
1625
1626 uint32_t policyFlags = 0;
1627 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1628 if (initialDown || buttonsPressed) {
1629 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001630 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001631 getContext()->fadePointer();
1632 }
1633
1634 if (mParameters.wake) {
1635 policyFlags |= POLICY_FLAG_WAKE;
1636 }
1637 }
1638
1639 // Consume raw off-screen touches before cooking pointer data.
1640 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001641 bool consumed;
1642 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1643 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001644 mCurrentRawState.rawPointerData.clear();
1645 }
1646
1647 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1648 // with cooked pointer data that has the same ids and indices as the raw data.
1649 // The following code can use either the raw or cooked data, as needed.
1650 cookPointerData();
1651
1652 // Apply stylus pressure to current cooked state.
1653 applyExternalStylusTouchState(when);
1654
1655 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001656 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1657 mSource, mViewport.displayId, policyFlags,
1658 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001659
1660 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001661 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001662 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1663 uint32_t id = idBits.clearFirstMarkedBit();
1664 const RawPointerData::Pointer& pointer =
1665 mCurrentRawState.rawPointerData.pointerForId(id);
1666 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1667 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1668 mCurrentCookedState.stylusIdBits.markBit(id);
1669 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1670 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1671 mCurrentCookedState.fingerIdBits.markBit(id);
1672 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1673 mCurrentCookedState.mouseIdBits.markBit(id);
1674 }
1675 }
1676 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1677 uint32_t id = idBits.clearFirstMarkedBit();
1678 const RawPointerData::Pointer& pointer =
1679 mCurrentRawState.rawPointerData.pointerForId(id);
1680 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1681 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1682 mCurrentCookedState.stylusIdBits.markBit(id);
1683 }
1684 }
1685
1686 // Stylus takes precedence over all tools, then mouse, then finger.
1687 PointerUsage pointerUsage = mPointerUsage;
1688 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1689 mCurrentCookedState.mouseIdBits.clear();
1690 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001691 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001692 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1693 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001694 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001695 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1696 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001697 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001698 }
1699
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001700 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001701 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001702 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001703 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001704 out += dispatchButtonRelease(when, readTime, policyFlags);
1705 out += dispatchHoverExit(when, readTime, policyFlags);
1706 out += dispatchTouches(when, readTime, policyFlags);
1707 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1708 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001709 }
1710
1711 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1712 mCurrentMotionAborted = false;
1713 }
1714 }
1715
1716 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001717 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1718 mSource, mViewport.displayId, policyFlags,
1719 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001720
1721 // Clear some transient state.
1722 mCurrentRawState.rawVScroll = 0;
1723 mCurrentRawState.rawHScroll = 0;
1724
1725 // Copy current touch to last touch in preparation for the next cycle.
1726 mLastRawState.copyFrom(mCurrentRawState);
1727 mLastCookedState.copyFrom(mCurrentCookedState);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001728 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001729}
1730
Garfield Tanc734e4f2021-01-15 20:01:39 -08001731void TouchInputMapper::updateTouchSpots() {
1732 if (!mConfig.showTouches || mPointerController == nullptr) {
1733 return;
1734 }
1735
1736 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1737 // clear touch spots.
1738 if (mDeviceMode != DeviceMode::DIRECT &&
1739 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1740 return;
1741 }
1742
1743 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1744 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1745
1746 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001747 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1748 mCurrentCookedState.cookedPointerData.idToIndex,
1749 mCurrentCookedState.cookedPointerData.touchingIdBits,
1750 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001751}
1752
1753bool TouchInputMapper::isTouchScreen() {
1754 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1755 mParameters.hasAssociatedDisplay;
1756}
1757
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001758void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001759 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001760 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1761 }
1762}
1763
1764void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1765 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1766 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1767
1768 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1769 float pressure = mExternalStylusState.pressure;
1770 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1771 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1772 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1773 }
1774 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1775 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1776
1777 PointerProperties& properties =
1778 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1779 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1780 properties.toolType = mExternalStylusState.toolType;
1781 }
1782 }
1783}
1784
1785bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001786 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001787 return false;
1788 }
1789
1790 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1791 state.rawPointerData.pointerCount != 0;
1792 if (initialDown) {
1793 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001794 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001795 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1796 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001797 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001798 resetExternalStylus();
1799 } else {
1800 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1801 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1802 }
Harry Cutts45483602022-08-24 14:36:48 +00001803 ALOGD_IF(DEBUG_STYLUS_FUSION,
1804 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1805 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001806 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1807 return true;
1808 }
1809 }
1810
1811 // Check if the stylus pointer has gone up.
1812 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001813 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814 mExternalStylusId = -1;
1815 }
1816
1817 return false;
1818}
1819
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001820std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1821 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001822 if (mDeviceMode == DeviceMode::POINTER) {
1823 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001824 // Since this is a synthetic event, we can consider its latency to be zero
1825 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001826 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001827 }
Michael Wright227c5542020-07-02 18:30:52 +01001828 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001829 if (mExternalStylusFusionTimeout < when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001830 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001831 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1832 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1833 }
1834 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001835 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001836}
1837
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001838std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1839 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001840 mExternalStylusState.copyFrom(state);
1841 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1842 // We're either in the middle of a fused stream of data or we're waiting on data before
1843 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1844 // data.
1845 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001846 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001847 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001848 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001849}
1850
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001851std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1852 uint32_t policyFlags, bool& outConsumed) {
1853 outConsumed = false;
1854 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001855 // Check for release of a virtual key.
1856 if (mCurrentVirtualKey.down) {
1857 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1858 // Pointer went up while virtual key was down.
1859 mCurrentVirtualKey.down = false;
1860 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001861 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1862 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1863 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001864 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1865 AKEY_EVENT_FLAG_FROM_SYSTEM |
1866 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001867 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001868 outConsumed = true;
1869 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001870 }
1871
1872 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1873 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1874 const RawPointerData::Pointer& pointer =
1875 mCurrentRawState.rawPointerData.pointerForId(id);
1876 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1877 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1878 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001879 outConsumed = true;
1880 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001881 }
1882 }
1883
1884 // Pointer left virtual key area or another pointer also went down.
1885 // Send key cancellation but do not consume the touch yet.
1886 // This is useful when the user swipes through from the virtual key area
1887 // into the main display surface.
1888 mCurrentVirtualKey.down = false;
1889 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001890 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1891 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001892 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1893 AKEY_EVENT_FLAG_FROM_SYSTEM |
1894 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1895 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001896 }
1897 }
1898
1899 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1900 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1901 // Pointer just went down. Check for virtual key press or off-screen touches.
1902 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1903 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001904 // Skip checking whether the pointer is inside the physical frame if the device is in
1905 // unscaled mode.
1906 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1907 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001908 // If exactly one pointer went down, check for virtual key hit.
1909 // Otherwise we will drop the entire stroke.
1910 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1911 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1912 if (virtualKey) {
1913 mCurrentVirtualKey.down = true;
1914 mCurrentVirtualKey.downTime = when;
1915 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1916 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1917 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001918 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1919 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001920
1921 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001922 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1923 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1924 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001925 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1926 AKEY_EVENT_ACTION_DOWN,
1927 AKEY_EVENT_FLAG_FROM_SYSTEM |
1928 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001929 }
1930 }
1931 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001932 outConsumed = true;
1933 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001934 }
1935 }
1936
1937 // Disable all virtual key touches that happen within a short time interval of the
1938 // most recent touch within the screen area. The idea is to filter out stray
1939 // virtual key presses when interacting with the touch screen.
1940 //
1941 // Problems we're trying to solve:
1942 //
1943 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1944 // virtual key area that is implemented by a separate touch panel and accidentally
1945 // triggers a virtual key.
1946 //
1947 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1948 // area and accidentally triggers a virtual key. This often happens when virtual keys
1949 // are layed out below the screen near to where the on screen keyboard's space bar
1950 // is displayed.
1951 if (mConfig.virtualKeyQuietTime > 0 &&
1952 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001953 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001954 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001955 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001956}
1957
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001958NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1959 uint32_t policyFlags, int32_t keyEventAction,
1960 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001961 int32_t keyCode = mCurrentVirtualKey.keyCode;
1962 int32_t scanCode = mCurrentVirtualKey.scanCode;
1963 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001964 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001965 policyFlags |= POLICY_FLAG_VIRTUAL;
1966
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001967 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1968 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1969 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001970}
1971
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001972std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1973 uint32_t policyFlags) {
1974 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001975 if (mCurrentMotionAborted) {
1976 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001977 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001978 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001979 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1980 if (!currentIdBits.isEmpty()) {
1981 int32_t metaState = getContext()->getGlobalMetaState();
1982 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001983 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001984 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1985 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001986 mCurrentCookedState.cookedPointerData.pointerProperties,
1987 mCurrentCookedState.cookedPointerData.pointerCoords,
1988 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1989 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1990 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001991 mCurrentMotionAborted = true;
1992 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001993 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001994}
1995
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001996std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1997 uint32_t policyFlags) {
1998 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001999 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2000 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2001 int32_t metaState = getContext()->getGlobalMetaState();
2002 int32_t buttonState = mCurrentCookedState.buttonState;
2003
2004 if (currentIdBits == lastIdBits) {
2005 if (!currentIdBits.isEmpty()) {
2006 // No pointer id changes so this is a move event.
2007 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002008 out.push_back(
2009 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2010 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2011 mCurrentCookedState.cookedPointerData.pointerProperties,
2012 mCurrentCookedState.cookedPointerData.pointerCoords,
2013 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2014 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2015 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002016 }
2017 } else {
2018 // There may be pointers going up and pointers going down and pointers moving
2019 // all at the same time.
2020 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2021 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2022 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2023 BitSet32 dispatchedIdBits(lastIdBits.value);
2024
2025 // Update last coordinates of pointers that have moved so that we observe the new
2026 // pointer positions at the same time as other pointers that have just gone up.
2027 bool moveNeeded =
2028 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2029 mCurrentCookedState.cookedPointerData.pointerCoords,
2030 mCurrentCookedState.cookedPointerData.idToIndex,
2031 mLastCookedState.cookedPointerData.pointerProperties,
2032 mLastCookedState.cookedPointerData.pointerCoords,
2033 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2034 if (buttonState != mLastCookedState.buttonState) {
2035 moveNeeded = true;
2036 }
2037
2038 // Dispatch pointer up events.
2039 while (!upIdBits.isEmpty()) {
2040 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002041 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002042 if (isCanceled) {
2043 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2044 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002045 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2046 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2047 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2048 buttonState, 0,
2049 mLastCookedState.cookedPointerData.pointerProperties,
2050 mLastCookedState.cookedPointerData.pointerCoords,
2051 mLastCookedState.cookedPointerData.idToIndex,
2052 dispatchedIdBits, upId, mOrientedXPrecision,
2053 mOrientedYPrecision, mDownTime,
2054 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002055 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002056 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002057 }
2058
2059 // Dispatch move events if any of the remaining pointers moved from their old locations.
2060 // Although applications receive new locations as part of individual pointer up
2061 // events, they do not generally handle them except when presented in a move event.
2062 if (moveNeeded && !moveIdBits.isEmpty()) {
2063 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002064 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2065 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2066 mCurrentCookedState.cookedPointerData.pointerProperties,
2067 mCurrentCookedState.cookedPointerData.pointerCoords,
2068 mCurrentCookedState.cookedPointerData.idToIndex,
2069 dispatchedIdBits, -1, mOrientedXPrecision,
2070 mOrientedYPrecision, mDownTime,
2071 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002072 }
2073
2074 // Dispatch pointer down events using the new pointer locations.
2075 while (!downIdBits.isEmpty()) {
2076 uint32_t downId = downIdBits.clearFirstMarkedBit();
2077 dispatchedIdBits.markBit(downId);
2078
2079 if (dispatchedIdBits.count() == 1) {
2080 // First pointer is going down. Set down time.
2081 mDownTime = when;
2082 }
2083
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002084 out.push_back(
2085 dispatchMotion(when, readTime, policyFlags, mSource,
2086 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2087 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2088 mCurrentCookedState.cookedPointerData.pointerCoords,
2089 mCurrentCookedState.cookedPointerData.idToIndex,
2090 dispatchedIdBits, downId, mOrientedXPrecision,
2091 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002092 }
2093 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002094 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002095}
2096
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002097std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2098 uint32_t policyFlags) {
2099 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002100 if (mSentHoverEnter &&
2101 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2102 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2103 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002104 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2105 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2106 mLastCookedState.buttonState, 0,
2107 mLastCookedState.cookedPointerData.pointerProperties,
2108 mLastCookedState.cookedPointerData.pointerCoords,
2109 mLastCookedState.cookedPointerData.idToIndex,
2110 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2111 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2112 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113 mSentHoverEnter = false;
2114 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002115 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002116}
2117
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002118std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2119 uint32_t policyFlags) {
2120 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002121 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2122 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2123 int32_t metaState = getContext()->getGlobalMetaState();
2124 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002125 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2126 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2127 mCurrentRawState.buttonState, 0,
2128 mCurrentCookedState.cookedPointerData.pointerProperties,
2129 mCurrentCookedState.cookedPointerData.pointerCoords,
2130 mCurrentCookedState.cookedPointerData.idToIndex,
2131 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2132 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2133 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002134 mSentHoverEnter = true;
2135 }
2136
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002137 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2138 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2139 mCurrentRawState.buttonState, 0,
2140 mCurrentCookedState.cookedPointerData.pointerProperties,
2141 mCurrentCookedState.cookedPointerData.pointerCoords,
2142 mCurrentCookedState.cookedPointerData.idToIndex,
2143 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2144 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2145 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002146 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002147 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002148}
2149
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002150std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2151 uint32_t policyFlags) {
2152 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002153 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2154 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2155 const int32_t metaState = getContext()->getGlobalMetaState();
2156 int32_t buttonState = mLastCookedState.buttonState;
2157 while (!releasedButtons.isEmpty()) {
2158 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2159 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002160 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2161 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2162 metaState, buttonState, 0,
2163 mCurrentCookedState.cookedPointerData.pointerProperties,
2164 mCurrentCookedState.cookedPointerData.pointerCoords,
2165 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2166 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2167 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002168 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002169 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170}
2171
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002172std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2173 uint32_t policyFlags) {
2174 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002175 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2176 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2177 const int32_t metaState = getContext()->getGlobalMetaState();
2178 int32_t buttonState = mLastCookedState.buttonState;
2179 while (!pressedButtons.isEmpty()) {
2180 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2181 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002182 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2183 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2184 buttonState, 0,
2185 mCurrentCookedState.cookedPointerData.pointerProperties,
2186 mCurrentCookedState.cookedPointerData.pointerCoords,
2187 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2188 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2189 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002190 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002191 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002192}
2193
2194const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2195 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2196 return cookedPointerData.touchingIdBits;
2197 }
2198 return cookedPointerData.hoveringIdBits;
2199}
2200
2201void TouchInputMapper::cookPointerData() {
2202 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2203
2204 mCurrentCookedState.cookedPointerData.clear();
2205 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2206 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2207 mCurrentRawState.rawPointerData.hoveringIdBits;
2208 mCurrentCookedState.cookedPointerData.touchingIdBits =
2209 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002210 mCurrentCookedState.cookedPointerData.canceledIdBits =
2211 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002212
2213 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2214 mCurrentCookedState.buttonState = 0;
2215 } else {
2216 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2217 }
2218
2219 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002220 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002221 for (uint32_t i = 0; i < currentPointerCount; i++) {
2222 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2223
2224 // Size
2225 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2226 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002227 case Calibration::SizeCalibration::GEOMETRIC:
2228 case Calibration::SizeCalibration::DIAMETER:
2229 case Calibration::SizeCalibration::BOX:
2230 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002231 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2232 touchMajor = in.touchMajor;
2233 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2234 toolMajor = in.toolMajor;
2235 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2236 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2237 : in.touchMajor;
2238 } else if (mRawPointerAxes.touchMajor.valid) {
2239 toolMajor = touchMajor = in.touchMajor;
2240 toolMinor = touchMinor =
2241 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2242 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2243 : in.touchMajor;
2244 } else if (mRawPointerAxes.toolMajor.valid) {
2245 touchMajor = toolMajor = in.toolMajor;
2246 touchMinor = toolMinor =
2247 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2248 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2249 : in.toolMajor;
2250 } else {
2251 ALOG_ASSERT(false,
2252 "No touch or tool axes. "
2253 "Size calibration should have been resolved to NONE.");
2254 touchMajor = 0;
2255 touchMinor = 0;
2256 toolMajor = 0;
2257 toolMinor = 0;
2258 size = 0;
2259 }
2260
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002261 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002262 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2263 if (touchingCount > 1) {
2264 touchMajor /= touchingCount;
2265 touchMinor /= touchingCount;
2266 toolMajor /= touchingCount;
2267 toolMinor /= touchingCount;
2268 size /= touchingCount;
2269 }
2270 }
2271
Michael Wright227c5542020-07-02 18:30:52 +01002272 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002273 touchMajor *= mGeometricScale;
2274 touchMinor *= mGeometricScale;
2275 toolMajor *= mGeometricScale;
2276 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002277 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002278 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2279 touchMinor = touchMajor;
2280 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2281 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002282 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002283 touchMinor = touchMajor;
2284 toolMinor = toolMajor;
2285 }
2286
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002287 mCalibration.applySizeScaleAndBias(touchMajor);
2288 mCalibration.applySizeScaleAndBias(touchMinor);
2289 mCalibration.applySizeScaleAndBias(toolMajor);
2290 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002291 size *= mSizeScale;
2292 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002293 case Calibration::SizeCalibration::DEFAULT:
2294 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2295 break;
2296 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 touchMajor = 0;
2298 touchMinor = 0;
2299 toolMajor = 0;
2300 toolMinor = 0;
2301 size = 0;
2302 break;
2303 }
2304
2305 // Pressure
2306 float pressure;
2307 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002308 case Calibration::PressureCalibration::PHYSICAL:
2309 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002310 pressure = in.pressure * mPressureScale;
2311 break;
2312 default:
2313 pressure = in.isHovering ? 0 : 1;
2314 break;
2315 }
2316
2317 // Tilt and Orientation
2318 float tilt;
2319 float orientation;
2320 if (mHaveTilt) {
2321 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2322 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2323 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2324 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2325 } else {
2326 tilt = 0;
2327
2328 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002329 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002330 orientation = in.orientation * mOrientationScale;
2331 break;
Michael Wright227c5542020-07-02 18:30:52 +01002332 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002333 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2334 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2335 if (c1 != 0 || c2 != 0) {
2336 orientation = atan2f(c1, c2) * 0.5f;
2337 float confidence = hypotf(c1, c2);
2338 float scale = 1.0f + confidence / 16.0f;
2339 touchMajor *= scale;
2340 touchMinor /= scale;
2341 toolMajor *= scale;
2342 toolMinor /= scale;
2343 } else {
2344 orientation = 0;
2345 }
2346 break;
2347 }
2348 default:
2349 orientation = 0;
2350 }
2351 }
2352
2353 // Distance
2354 float distance;
2355 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002356 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002357 distance = in.distance * mDistanceScale;
2358 break;
2359 default:
2360 distance = 0;
2361 }
2362
2363 // Coverage
2364 int32_t rawLeft, rawTop, rawRight, rawBottom;
2365 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002366 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2368 rawRight = in.toolMinor & 0x0000ffff;
2369 rawBottom = in.toolMajor & 0x0000ffff;
2370 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2371 break;
2372 default:
2373 rawLeft = rawTop = rawRight = rawBottom = 0;
2374 break;
2375 }
2376
2377 // Adjust X,Y coords for device calibration
2378 // TODO: Adjust coverage coords?
2379 float xTransformed = in.x, yTransformed = in.y;
2380 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002381 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382
Prabir Pradhan1728b212021-10-19 16:00:03 -07002383 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 float left, top, right, bottom;
2385
Prabir Pradhan1728b212021-10-19 16:00:03 -07002386 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002388 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2389 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2390 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2391 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002393 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002395 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 }
2397 break;
2398 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002399 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2400 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002401 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2402 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002404 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002406 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002407 }
2408 break;
2409 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2411 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002412 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2413 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002414 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002415 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002416 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002417 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 }
2419 break;
2420 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002421 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2422 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2423 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2424 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 break;
2426 }
2427
2428 // Write output coords.
2429 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2430 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002431 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2432 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002433 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2434 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2435 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2436 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2437 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2438 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2439 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002440 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002441 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2442 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2443 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2444 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2445 } else {
2446 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2447 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2448 }
2449
Chris Ye364fdb52020-08-05 15:07:56 -07002450 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002451 uint32_t id = in.id;
2452 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2453 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2454 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2455 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2456 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2457 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2458 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2459 }
2460
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 // Write output properties.
2462 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 properties.clear();
2464 properties.id = id;
2465 properties.toolType = in.toolType;
2466
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002467 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002469 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 }
2471}
2472
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2474 uint32_t policyFlags,
2475 PointerUsage pointerUsage) {
2476 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002477 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002478 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 mPointerUsage = pointerUsage;
2480 }
2481
2482 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002483 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002484 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 break;
Michael Wright227c5542020-07-02 18:30:52 +01002486 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002487 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002488 break;
Michael Wright227c5542020-07-02 18:30:52 +01002489 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002490 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491 break;
Michael Wright227c5542020-07-02 18:30:52 +01002492 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002493 break;
2494 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002495 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496}
2497
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002498std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2499 uint32_t policyFlags) {
2500 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002501 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002502 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002503 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 break;
Michael Wright227c5542020-07-02 18:30:52 +01002505 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002506 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002507 break;
Michael Wright227c5542020-07-02 18:30:52 +01002508 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002509 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002510 break;
Michael Wright227c5542020-07-02 18:30:52 +01002511 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 break;
2513 }
2514
Michael Wright227c5542020-07-02 18:30:52 +01002515 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002516 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002517}
2518
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002519std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2520 uint32_t policyFlags,
2521 bool isTimeout) {
2522 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002523 // Update current gesture coordinates.
2524 bool cancelPreviousGesture, finishPreviousGesture;
2525 bool sendEvents =
2526 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2527 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002528 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002529 }
2530 if (finishPreviousGesture) {
2531 cancelPreviousGesture = false;
2532 }
2533
2534 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002535 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002536 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002537 if (finishPreviousGesture || cancelPreviousGesture) {
2538 mPointerController->clearSpots();
2539 }
2540
Michael Wright227c5542020-07-02 18:30:52 +01002541 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002542 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2543 mPointerGesture.currentGestureIdToIndex,
2544 mPointerGesture.currentGestureIdBits,
2545 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002546 }
2547 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002548 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002549 }
2550
2551 // Show or hide the pointer if needed.
2552 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002553 case PointerGesture::Mode::NEUTRAL:
2554 case PointerGesture::Mode::QUIET:
2555 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2556 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002557 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002558 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002559 }
2560 break;
Michael Wright227c5542020-07-02 18:30:52 +01002561 case PointerGesture::Mode::TAP:
2562 case PointerGesture::Mode::TAP_DRAG:
2563 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2564 case PointerGesture::Mode::HOVER:
2565 case PointerGesture::Mode::PRESS:
2566 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002567 // Unfade the pointer when the current gesture manipulates the
2568 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002569 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002570 break;
Michael Wright227c5542020-07-02 18:30:52 +01002571 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002572 // Fade the pointer when the current gesture manipulates a different
2573 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002574 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002575 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002576 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002577 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002578 }
2579 break;
2580 }
2581
2582 // Send events!
2583 int32_t metaState = getContext()->getGlobalMetaState();
2584 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002585 const MotionClassification classification =
2586 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2587 ? MotionClassification::TWO_FINGER_SWIPE
2588 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002589
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002590 uint32_t flags = 0;
2591
2592 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2593 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2594 }
2595
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002596 // Update last coordinates of pointers that have moved so that we observe the new
2597 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002598 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2599 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2600 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2601 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2602 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2603 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002604 bool moveNeeded = false;
2605 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2606 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2607 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2608 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2609 mPointerGesture.lastGestureIdBits.value);
2610 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2611 mPointerGesture.currentGestureCoords,
2612 mPointerGesture.currentGestureIdToIndex,
2613 mPointerGesture.lastGestureProperties,
2614 mPointerGesture.lastGestureCoords,
2615 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2616 if (buttonState != mLastCookedState.buttonState) {
2617 moveNeeded = true;
2618 }
2619 }
2620
2621 // Send motion events for all pointers that went up or were canceled.
2622 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2623 if (!dispatchedGestureIdBits.isEmpty()) {
2624 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002625 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002626 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002627 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002628 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2629 mPointerGesture.lastGestureProperties,
2630 mPointerGesture.lastGestureCoords,
2631 mPointerGesture.lastGestureIdToIndex,
2632 dispatchedGestureIdBits, -1, 0, 0,
2633 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002634
2635 dispatchedGestureIdBits.clear();
2636 } else {
2637 BitSet32 upGestureIdBits;
2638 if (finishPreviousGesture) {
2639 upGestureIdBits = dispatchedGestureIdBits;
2640 } else {
2641 upGestureIdBits.value =
2642 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2643 }
2644 while (!upGestureIdBits.isEmpty()) {
2645 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2646
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002647 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2648 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2649 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2650 mPointerGesture.lastGestureProperties,
2651 mPointerGesture.lastGestureCoords,
2652 mPointerGesture.lastGestureIdToIndex,
2653 dispatchedGestureIdBits, id, 0, 0,
2654 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002655
2656 dispatchedGestureIdBits.clearBit(id);
2657 }
2658 }
2659 }
2660
2661 // Send motion events for all pointers that moved.
2662 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002663 out.push_back(
2664 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2665 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2666 mPointerGesture.currentGestureProperties,
2667 mPointerGesture.currentGestureCoords,
2668 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2669 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002670 }
2671
2672 // Send motion events for all pointers that went down.
2673 if (down) {
2674 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2675 ~dispatchedGestureIdBits.value);
2676 while (!downGestureIdBits.isEmpty()) {
2677 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2678 dispatchedGestureIdBits.markBit(id);
2679
2680 if (dispatchedGestureIdBits.count() == 1) {
2681 mPointerGesture.downTime = when;
2682 }
2683
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002684 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2685 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2686 buttonState, 0, mPointerGesture.currentGestureProperties,
2687 mPointerGesture.currentGestureCoords,
2688 mPointerGesture.currentGestureIdToIndex,
2689 dispatchedGestureIdBits, id, 0, 0,
2690 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002691 }
2692 }
2693
2694 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002695 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002696 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2697 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2698 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2699 mPointerGesture.currentGestureProperties,
2700 mPointerGesture.currentGestureCoords,
2701 mPointerGesture.currentGestureIdToIndex,
2702 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2703 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002704 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2705 // Synthesize a hover move event after all pointers go up to indicate that
2706 // the pointer is hovering again even if the user is not currently touching
2707 // the touch pad. This ensures that a view will receive a fresh hover enter
2708 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002709 float x, y;
2710 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002711
2712 PointerProperties pointerProperties;
2713 pointerProperties.clear();
2714 pointerProperties.id = 0;
2715 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2716
2717 PointerCoords pointerCoords;
2718 pointerCoords.clear();
2719 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2720 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2721
2722 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002723 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2724 mSource, displayId, policyFlags,
2725 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2726 buttonState, MotionClassification::NONE,
2727 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2728 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2729 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002730 }
2731
2732 // Update state.
2733 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2734 if (!down) {
2735 mPointerGesture.lastGestureIdBits.clear();
2736 } else {
2737 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2738 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2739 uint32_t id = idBits.clearFirstMarkedBit();
2740 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2741 mPointerGesture.lastGestureProperties[index].copyFrom(
2742 mPointerGesture.currentGestureProperties[index]);
2743 mPointerGesture.lastGestureCoords[index].copyFrom(
2744 mPointerGesture.currentGestureCoords[index]);
2745 mPointerGesture.lastGestureIdToIndex[id] = index;
2746 }
2747 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002748 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002749}
2750
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002751std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2752 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002753 const MotionClassification classification =
2754 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2755 ? MotionClassification::TWO_FINGER_SWIPE
2756 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002757 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002758 // Cancel previously dispatches pointers.
2759 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2760 int32_t metaState = getContext()->getGlobalMetaState();
2761 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002762 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002763 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2764 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002765 mPointerGesture.lastGestureProperties,
2766 mPointerGesture.lastGestureCoords,
2767 mPointerGesture.lastGestureIdToIndex,
2768 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2769 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002770 }
2771
2772 // Reset the current pointer gesture.
2773 mPointerGesture.reset();
2774 mPointerVelocityControl.reset();
2775
2776 // Remove any current spots.
2777 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002778 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002779 mPointerController->clearSpots();
2780 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002781 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002782}
2783
2784bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2785 bool* outFinishPreviousGesture, bool isTimeout) {
2786 *outCancelPreviousGesture = false;
2787 *outFinishPreviousGesture = false;
2788
2789 // Handle TAP timeout.
2790 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002791 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002792
Michael Wright227c5542020-07-02 18:30:52 +01002793 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2795 // The tap/drag timeout has not yet expired.
2796 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2797 mConfig.pointerGestureTapDragInterval);
2798 } else {
2799 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002800 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002801 *outFinishPreviousGesture = true;
2802
2803 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002804 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002805 mPointerGesture.currentGestureIdBits.clear();
2806
2807 mPointerVelocityControl.reset();
2808 return true;
2809 }
2810 }
2811
2812 // We did not handle this timeout.
2813 return false;
2814 }
2815
2816 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2817 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2818
2819 // Update the velocity tracker.
2820 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002821 std::vector<float> positionsX;
2822 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002823 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824 uint32_t id = idBits.clearFirstMarkedBit();
2825 const RawPointerData::Pointer& pointer =
2826 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002827 positionsX.push_back(pointer.x * mPointerXMovementScale);
2828 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002829 }
2830 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002831 {{AMOTION_EVENT_AXIS_X, positionsX},
2832 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002833 }
2834
2835 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2836 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002837 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2838 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2839 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002840 mPointerGesture.resetTap();
2841 }
2842
2843 // Pick a new active touch id if needed.
2844 // Choose an arbitrary pointer that just went down, if there is one.
2845 // Otherwise choose an arbitrary remaining pointer.
2846 // This guarantees we always have an active touch id when there is at least one pointer.
2847 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002848 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002850 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002851 mPointerGesture.firstTouchTime = when;
2852 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002853 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2854 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2855 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2856 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002858 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859
2860 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002861 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002862 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002863 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2864 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2865 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002866 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 *outFinishPreviousGesture = true;
2868 }
2869
2870 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002871 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 mPointerGesture.currentGestureIdBits.clear();
2873
2874 mPointerVelocityControl.reset();
2875 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2876 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2877 // The pointer follows the active touch point.
2878 // Emit DOWN, MOVE, UP events at the pointer location.
2879 //
2880 // Only the active touch matters; other fingers are ignored. This policy helps
2881 // to handle the case where the user places a second finger on the touch pad
2882 // to apply the necessary force to depress an integrated button below the surface.
2883 // We don't want the second finger to be delivered to applications.
2884 //
2885 // For this to work well, we need to make sure to track the pointer that is really
2886 // active. If the user first puts one finger down to click then adds another
2887 // finger to drag then the active pointer should switch to the finger that is
2888 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002889 ALOGD_IF(DEBUG_GESTURES,
2890 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2891 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002893 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002894 *outFinishPreviousGesture = true;
2895 mPointerGesture.activeGestureId = 0;
2896 }
2897
2898 // Switch pointers if needed.
2899 // Find the fastest pointer and follow it.
2900 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002901 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002902 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002903 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002904 ALOGD_IF(DEBUG_GESTURES,
2905 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2906 "bestSpeed=%0.3f",
2907 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002908 }
2909 }
2910
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002911 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002912 // When using spots, the click will occur at the position of the anchor
2913 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002914 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002915 } else {
2916 mPointerVelocityControl.reset();
2917 }
2918
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002919 float x, y;
2920 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002921
Michael Wright227c5542020-07-02 18:30:52 +01002922 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002923 mPointerGesture.currentGestureIdBits.clear();
2924 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2925 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2926 mPointerGesture.currentGestureProperties[0].clear();
2927 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2928 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2929 mPointerGesture.currentGestureCoords[0].clear();
2930 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2931 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2932 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2933 } else if (currentFingerCount == 0) {
2934 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002935 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002936 *outFinishPreviousGesture = true;
2937 }
2938
2939 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2940 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2941 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002942 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2943 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 lastFingerCount == 1) {
2945 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002946 float x, y;
2947 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002948 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2949 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002950 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951
2952 mPointerGesture.tapUpTime = when;
2953 getContext()->requestTimeoutAtTime(when +
2954 mConfig.pointerGestureTapDragInterval);
2955
2956 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002957 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958 mPointerGesture.currentGestureIdBits.clear();
2959 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2960 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2961 mPointerGesture.currentGestureProperties[0].clear();
2962 mPointerGesture.currentGestureProperties[0].id =
2963 mPointerGesture.activeGestureId;
2964 mPointerGesture.currentGestureProperties[0].toolType =
2965 AMOTION_EVENT_TOOL_TYPE_FINGER;
2966 mPointerGesture.currentGestureCoords[0].clear();
2967 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2968 mPointerGesture.tapX);
2969 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2970 mPointerGesture.tapY);
2971 mPointerGesture.currentGestureCoords[0]
2972 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2973
2974 tapped = true;
2975 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002976 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2977 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978 }
2979 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002980 if (DEBUG_GESTURES) {
2981 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2982 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2983 (when - mPointerGesture.tapDownTime) * 0.000001f);
2984 } else {
2985 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2986 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002987 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 }
2989 }
2990
2991 mPointerVelocityControl.reset();
2992
2993 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002994 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002995 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002996 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 mPointerGesture.currentGestureIdBits.clear();
2998 }
2999 } else if (currentFingerCount == 1) {
3000 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3001 // The pointer follows the active touch point.
3002 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3003 // When in TAP_DRAG, emit MOVE events at the pointer location.
3004 ALOG_ASSERT(activeTouchId >= 0);
3005
Michael Wright227c5542020-07-02 18:30:52 +01003006 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3007 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003008 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003009 float x, y;
3010 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003011 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3012 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003013 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003014 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003015 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3016 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003017 }
3018 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003019 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3020 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003021 }
Michael Wright227c5542020-07-02 18:30:52 +01003022 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3023 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003024 }
3025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003026 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003027 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003028 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003029 } else {
3030 mPointerVelocityControl.reset();
3031 }
3032
3033 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003034 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003035 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003036 down = true;
3037 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003038 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003039 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003040 *outFinishPreviousGesture = true;
3041 }
3042 mPointerGesture.activeGestureId = 0;
3043 down = false;
3044 }
3045
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003046 float x, y;
3047 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003048
3049 mPointerGesture.currentGestureIdBits.clear();
3050 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3051 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3052 mPointerGesture.currentGestureProperties[0].clear();
3053 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3054 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3055 mPointerGesture.currentGestureCoords[0].clear();
3056 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3057 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3058 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3059 down ? 1.0f : 0.0f);
3060
3061 if (lastFingerCount == 0 && currentFingerCount != 0) {
3062 mPointerGesture.resetTap();
3063 mPointerGesture.tapDownTime = when;
3064 mPointerGesture.tapX = x;
3065 mPointerGesture.tapY = y;
3066 }
3067 } else {
3068 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003069 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003070 }
3071
3072 mPointerController->setButtonState(mCurrentRawState.buttonState);
3073
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003074 if (DEBUG_GESTURES) {
3075 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3076 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3077 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3078 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3079 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3080 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3081 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3082 uint32_t id = idBits.clearFirstMarkedBit();
3083 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3084 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3085 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3086 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3087 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3088 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3089 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3090 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3091 }
3092 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3093 uint32_t id = idBits.clearFirstMarkedBit();
3094 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3095 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3096 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3097 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3098 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3099 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3100 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3101 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3102 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003103 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003104 return true;
3105}
3106
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003107bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3108 if (mPointerGesture.activeTouchId < 0) {
3109 mPointerGesture.resetQuietTime();
3110 return false;
3111 }
3112
3113 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3114 return true;
3115 }
3116
3117 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3118 bool isQuietTime = false;
3119 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3120 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3121 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3122 currentFingerCount < 2) {
3123 // Enter quiet time when exiting swipe or freeform state.
3124 // This is to prevent accidentally entering the hover state and flinging the
3125 // pointer when finishing a swipe and there is still one pointer left onscreen.
3126 isQuietTime = true;
3127 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3128 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3129 // Enter quiet time when releasing the button and there are still two or more
3130 // fingers down. This may indicate that one finger was used to press the button
3131 // but it has not gone up yet.
3132 isQuietTime = true;
3133 }
3134 if (isQuietTime) {
3135 mPointerGesture.quietTime = when;
3136 }
3137 return isQuietTime;
3138}
3139
3140std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3141 int32_t bestId = -1;
3142 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3143 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3144 uint32_t id = idBits.clearFirstMarkedBit();
3145 std::optional<float> vx =
3146 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3147 std::optional<float> vy =
3148 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3149 if (vx && vy) {
3150 float speed = hypotf(*vx, *vy);
3151 if (speed > bestSpeed) {
3152 bestId = id;
3153 bestSpeed = speed;
3154 }
3155 }
3156 }
3157 return std::make_pair(bestId, bestSpeed);
3158}
3159
3160void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3161 bool* finishPreviousGesture) {
3162 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3163 // to move before deciding what to do.
3164 //
3165 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3166 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3167 // just a press or long-press at the pointer location.
3168 //
3169 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3170 // pointer location.
3171 //
3172 // When the two fingers move enough or when additional fingers are added, we make a decision to
3173 // transition into SWIPE or FREEFORM mode accordingly.
3174 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3175 ALOG_ASSERT(activeTouchId >= 0);
3176
3177 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3178 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3179 bool settled =
3180 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3181 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3182 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3183 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3184 *finishPreviousGesture = true;
3185 } else if (!settled && currentFingerCount > lastFingerCount) {
3186 // Additional pointers have gone down but not yet settled.
3187 // Reset the gesture.
3188 ALOGD_IF(DEBUG_GESTURES,
3189 "Gestures: Resetting gesture since additional pointers went down for "
3190 "MULTITOUCH, settle time remaining %0.3fms",
3191 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3192 when) * 0.000001f);
3193 *cancelPreviousGesture = true;
3194 } else {
3195 // Continue previous gesture.
3196 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3197 }
3198
3199 if (*finishPreviousGesture || *cancelPreviousGesture) {
3200 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3201 mPointerGesture.activeGestureId = 0;
3202 mPointerGesture.referenceIdBits.clear();
3203 mPointerVelocityControl.reset();
3204
3205 // Use the centroid and pointer location as the reference points for the gesture.
3206 ALOGD_IF(DEBUG_GESTURES,
3207 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3208 "%0.3fms",
3209 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3210 when) * 0.000001f);
3211 mCurrentRawState.rawPointerData
3212 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3213 &mPointerGesture.referenceTouchY);
3214 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3215 &mPointerGesture.referenceGestureY);
3216 }
3217
3218 // Clear the reference deltas for fingers not yet included in the reference calculation.
3219 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3220 ~mPointerGesture.referenceIdBits.value);
3221 !idBits.isEmpty();) {
3222 uint32_t id = idBits.clearFirstMarkedBit();
3223 mPointerGesture.referenceDeltas[id].dx = 0;
3224 mPointerGesture.referenceDeltas[id].dy = 0;
3225 }
3226 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3227
3228 // Add delta for all fingers and calculate a common movement delta.
3229 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3230 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3231 mCurrentCookedState.fingerIdBits.value);
3232 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3233 bool first = (idBits == commonIdBits);
3234 uint32_t id = idBits.clearFirstMarkedBit();
3235 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3236 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3237 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3238 delta.dx += cpd.x - lpd.x;
3239 delta.dy += cpd.y - lpd.y;
3240
3241 if (first) {
3242 commonDeltaRawX = delta.dx;
3243 commonDeltaRawY = delta.dy;
3244 } else {
3245 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3246 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3247 }
3248 }
3249
3250 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3251 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3252 float dist[MAX_POINTER_ID + 1];
3253 int32_t distOverThreshold = 0;
3254 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3255 uint32_t id = idBits.clearFirstMarkedBit();
3256 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3257 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3258 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3259 distOverThreshold += 1;
3260 }
3261 }
3262
3263 // Only transition when at least two pointers have moved further than
3264 // the minimum distance threshold.
3265 if (distOverThreshold >= 2) {
3266 if (currentFingerCount > 2) {
3267 // There are more than two pointers, switch to FREEFORM.
3268 ALOGD_IF(DEBUG_GESTURES,
3269 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3270 currentFingerCount);
3271 *cancelPreviousGesture = true;
3272 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3273 } else {
3274 // There are exactly two pointers.
3275 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3276 uint32_t id1 = idBits.clearFirstMarkedBit();
3277 uint32_t id2 = idBits.firstMarkedBit();
3278 const RawPointerData::Pointer& p1 =
3279 mCurrentRawState.rawPointerData.pointerForId(id1);
3280 const RawPointerData::Pointer& p2 =
3281 mCurrentRawState.rawPointerData.pointerForId(id2);
3282 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3283 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3284 // There are two pointers but they are too far apart for a SWIPE,
3285 // switch to FREEFORM.
3286 ALOGD_IF(DEBUG_GESTURES,
3287 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3288 mutualDistance, mPointerGestureMaxSwipeWidth);
3289 *cancelPreviousGesture = true;
3290 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3291 } else {
3292 // There are two pointers. Wait for both pointers to start moving
3293 // before deciding whether this is a SWIPE or FREEFORM gesture.
3294 float dist1 = dist[id1];
3295 float dist2 = dist[id2];
3296 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3297 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3298 // Calculate the dot product of the displacement vectors.
3299 // When the vectors are oriented in approximately the same direction,
3300 // the angle betweeen them is near zero and the cosine of the angle
3301 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3302 // mag(v2).
3303 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3304 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3305 float dx1 = delta1.dx * mPointerXZoomScale;
3306 float dy1 = delta1.dy * mPointerYZoomScale;
3307 float dx2 = delta2.dx * mPointerXZoomScale;
3308 float dy2 = delta2.dy * mPointerYZoomScale;
3309 float dot = dx1 * dx2 + dy1 * dy2;
3310 float cosine = dot / (dist1 * dist2); // denominator always > 0
3311 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3312 // Pointers are moving in the same direction. Switch to SWIPE.
3313 ALOGD_IF(DEBUG_GESTURES,
3314 "Gestures: PRESS transitioned to SWIPE, "
3315 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3316 "cosine %0.3f >= %0.3f",
3317 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3318 mConfig.pointerGestureMultitouchMinDistance, cosine,
3319 mConfig.pointerGestureSwipeTransitionAngleCosine);
3320 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3321 } else {
3322 // Pointers are moving in different directions. Switch to FREEFORM.
3323 ALOGD_IF(DEBUG_GESTURES,
3324 "Gestures: PRESS transitioned to FREEFORM, "
3325 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3326 "cosine %0.3f < %0.3f",
3327 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3328 mConfig.pointerGestureMultitouchMinDistance, cosine,
3329 mConfig.pointerGestureSwipeTransitionAngleCosine);
3330 *cancelPreviousGesture = true;
3331 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3332 }
3333 }
3334 }
3335 }
3336 }
3337 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3338 // Switch from SWIPE to FREEFORM if additional pointers go down.
3339 // Cancel previous gesture.
3340 if (currentFingerCount > 2) {
3341 ALOGD_IF(DEBUG_GESTURES,
3342 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3343 currentFingerCount);
3344 *cancelPreviousGesture = true;
3345 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3346 }
3347 }
3348
3349 // Move the reference points based on the overall group motion of the fingers
3350 // except in PRESS mode while waiting for a transition to occur.
3351 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3352 (commonDeltaRawX || commonDeltaRawY)) {
3353 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3354 uint32_t id = idBits.clearFirstMarkedBit();
3355 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3356 delta.dx = 0;
3357 delta.dy = 0;
3358 }
3359
3360 mPointerGesture.referenceTouchX += commonDeltaRawX;
3361 mPointerGesture.referenceTouchY += commonDeltaRawY;
3362
3363 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3364 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3365
3366 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3367 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3368
3369 mPointerGesture.referenceGestureX += commonDeltaX;
3370 mPointerGesture.referenceGestureY += commonDeltaY;
3371 }
3372
3373 // Report gestures.
3374 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3375 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3376 // PRESS or SWIPE mode.
3377 ALOGD_IF(DEBUG_GESTURES,
3378 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3379 "currentTouchPointerCount=%d",
3380 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3381 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3382
3383 mPointerGesture.currentGestureIdBits.clear();
3384 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3385 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3386 mPointerGesture.currentGestureProperties[0].clear();
3387 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3388 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3389 mPointerGesture.currentGestureCoords[0].clear();
3390 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3391 mPointerGesture.referenceGestureX);
3392 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3393 mPointerGesture.referenceGestureY);
3394 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3395 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3396 float xOffset = static_cast<float>(commonDeltaRawX) /
3397 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3398 float yOffset = static_cast<float>(commonDeltaRawY) /
3399 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3400 mPointerGesture.currentGestureCoords[0]
3401 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3402 mPointerGesture.currentGestureCoords[0]
3403 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3404 }
3405 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3406 // FREEFORM mode.
3407 ALOGD_IF(DEBUG_GESTURES,
3408 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3409 "currentTouchPointerCount=%d",
3410 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3411 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3412
3413 mPointerGesture.currentGestureIdBits.clear();
3414
3415 BitSet32 mappedTouchIdBits;
3416 BitSet32 usedGestureIdBits;
3417 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3418 // Initially, assign the active gesture id to the active touch point
3419 // if there is one. No other touch id bits are mapped yet.
3420 if (!*cancelPreviousGesture) {
3421 mappedTouchIdBits.markBit(activeTouchId);
3422 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3423 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3424 mPointerGesture.activeGestureId;
3425 } else {
3426 mPointerGesture.activeGestureId = -1;
3427 }
3428 } else {
3429 // Otherwise, assume we mapped all touches from the previous frame.
3430 // Reuse all mappings that are still applicable.
3431 mappedTouchIdBits.value =
3432 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3433 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3434
3435 // Check whether we need to choose a new active gesture id because the
3436 // current went went up.
3437 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3438 ~mCurrentCookedState.fingerIdBits.value);
3439 !upTouchIdBits.isEmpty();) {
3440 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3441 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3442 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3443 mPointerGesture.activeGestureId = -1;
3444 break;
3445 }
3446 }
3447 }
3448
3449 ALOGD_IF(DEBUG_GESTURES,
3450 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3451 "activeGestureId=%d",
3452 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3453
3454 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3455 for (uint32_t i = 0; i < currentFingerCount; i++) {
3456 uint32_t touchId = idBits.clearFirstMarkedBit();
3457 uint32_t gestureId;
3458 if (!mappedTouchIdBits.hasBit(touchId)) {
3459 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3460 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3461 ALOGD_IF(DEBUG_GESTURES,
3462 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3463 gestureId);
3464 } else {
3465 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3466 ALOGD_IF(DEBUG_GESTURES,
3467 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3468 touchId, gestureId);
3469 }
3470 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3471 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3472
3473 const RawPointerData::Pointer& pointer =
3474 mCurrentRawState.rawPointerData.pointerForId(touchId);
3475 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3476 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3477 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3478
3479 mPointerGesture.currentGestureProperties[i].clear();
3480 mPointerGesture.currentGestureProperties[i].id = gestureId;
3481 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3482 mPointerGesture.currentGestureCoords[i].clear();
3483 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3484 mPointerGesture.referenceGestureX +
3485 deltaX);
3486 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3487 mPointerGesture.referenceGestureY +
3488 deltaY);
3489 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3490 }
3491
3492 if (mPointerGesture.activeGestureId < 0) {
3493 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3494 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3495 mPointerGesture.activeGestureId);
3496 }
3497 }
3498}
3499
Harry Cutts714d1ad2022-08-24 16:36:43 +00003500void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3501 const RawPointerData::Pointer& currentPointer =
3502 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3503 const RawPointerData::Pointer& lastPointer =
3504 mLastRawState.rawPointerData.pointerForId(pointerId);
3505 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3506 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3507
3508 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3509 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3510
3511 mPointerController->move(deltaX, deltaY);
3512}
3513
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003514std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3515 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003516 mPointerSimple.currentCoords.clear();
3517 mPointerSimple.currentProperties.clear();
3518
3519 bool down, hovering;
3520 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3521 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3522 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003523 mPointerController
3524 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3525 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003526
3527 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3528 down = !hovering;
3529
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003530 float x, y;
3531 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003532 mPointerSimple.currentCoords.copyFrom(
3533 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3534 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3535 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3536 mPointerSimple.currentProperties.id = 0;
3537 mPointerSimple.currentProperties.toolType =
3538 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3539 } else {
3540 down = false;
3541 hovering = false;
3542 }
3543
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003544 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003545}
3546
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003547std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3548 uint32_t policyFlags) {
3549 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003550}
3551
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003552std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3553 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003554 mPointerSimple.currentCoords.clear();
3555 mPointerSimple.currentProperties.clear();
3556
3557 bool down, hovering;
3558 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3559 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003560 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003561 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003562 } else {
3563 mPointerVelocityControl.reset();
3564 }
3565
3566 down = isPointerDown(mCurrentRawState.buttonState);
3567 hovering = !down;
3568
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003569 float x, y;
3570 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003571 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572 mPointerSimple.currentCoords.copyFrom(
3573 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3574 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3575 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3576 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3577 hovering ? 0.0f : 1.0f);
3578 mPointerSimple.currentProperties.id = 0;
3579 mPointerSimple.currentProperties.toolType =
3580 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3581 } else {
3582 mPointerVelocityControl.reset();
3583
3584 down = false;
3585 hovering = false;
3586 }
3587
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003588 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589}
3590
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003591std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3592 uint32_t policyFlags) {
3593 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003594
3595 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003596
3597 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598}
3599
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003600std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3601 uint32_t policyFlags, bool down,
3602 bool hovering) {
3603 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003604 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003605
3606 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003607 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003608 mPointerController->clearSpots();
3609 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003610 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003611 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003612 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003613 }
Garfield Tan9514d782020-11-10 16:37:23 -08003614 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003615
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003616 float xCursorPosition, yCursorPosition;
3617 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003618
3619 if (mPointerSimple.down && !down) {
3620 mPointerSimple.down = false;
3621
3622 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003623 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3624 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3625 0, metaState, mLastRawState.buttonState,
3626 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3627 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3628 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3629 yCursorPosition, mPointerSimple.downTime,
3630 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003631 }
3632
3633 if (mPointerSimple.hovering && !hovering) {
3634 mPointerSimple.hovering = false;
3635
3636 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003637 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3638 mSource, displayId, policyFlags,
3639 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3640 mLastRawState.buttonState, MotionClassification::NONE,
3641 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3642 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3643 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3644 yCursorPosition, mPointerSimple.downTime,
3645 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003646 }
3647
3648 if (down) {
3649 if (!mPointerSimple.down) {
3650 mPointerSimple.down = true;
3651 mPointerSimple.downTime = when;
3652
3653 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003654 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3655 mSource, displayId, policyFlags,
3656 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3657 mCurrentRawState.buttonState, MotionClassification::NONE,
3658 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3659 &mPointerSimple.currentProperties,
3660 &mPointerSimple.currentCoords, mOrientedXPrecision,
3661 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3662 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003663 }
3664
3665 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003666 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3667 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3668 0, 0, metaState, mCurrentRawState.buttonState,
3669 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3670 &mPointerSimple.currentProperties,
3671 &mPointerSimple.currentCoords, mOrientedXPrecision,
3672 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3673 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003674 }
3675
3676 if (hovering) {
3677 if (!mPointerSimple.hovering) {
3678 mPointerSimple.hovering = true;
3679
3680 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003681 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3682 mSource, displayId, policyFlags,
3683 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3684 mCurrentRawState.buttonState, MotionClassification::NONE,
3685 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3686 &mPointerSimple.currentProperties,
3687 &mPointerSimple.currentCoords, mOrientedXPrecision,
3688 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3689 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003690 }
3691
3692 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003693 out.push_back(
3694 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3695 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3696 metaState, mCurrentRawState.buttonState,
3697 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3698 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3699 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3700 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003701 }
3702
3703 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3704 float vscroll = mCurrentRawState.rawVScroll;
3705 float hscroll = mCurrentRawState.rawHScroll;
3706 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3707 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3708
3709 // Send scroll.
3710 PointerCoords pointerCoords;
3711 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3712 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3713 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3714
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003715 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3716 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3717 0, 0, metaState, mCurrentRawState.buttonState,
3718 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3719 &mPointerSimple.currentProperties, &pointerCoords,
3720 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3721 yCursorPosition, mPointerSimple.downTime,
3722 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003723 }
3724
3725 // Save state.
3726 if (down || hovering) {
3727 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3728 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3729 } else {
3730 mPointerSimple.reset();
3731 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003732 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003733}
3734
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003735std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3736 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003737 mPointerSimple.currentCoords.clear();
3738 mPointerSimple.currentProperties.clear();
3739
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003740 return dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003741}
3742
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003743NotifyMotionArgs TouchInputMapper::dispatchMotion(
3744 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3745 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
3746 int32_t edgeFlags, const PointerProperties* properties, const PointerCoords* coords,
3747 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
3748 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003749 PointerCoords pointerCoords[MAX_POINTERS];
3750 PointerProperties pointerProperties[MAX_POINTERS];
3751 uint32_t pointerCount = 0;
3752 while (!idBits.isEmpty()) {
3753 uint32_t id = idBits.clearFirstMarkedBit();
3754 uint32_t index = idToIndex[id];
3755 pointerProperties[pointerCount].copyFrom(properties[index]);
3756 pointerCoords[pointerCount].copyFrom(coords[index]);
3757
3758 if (changedId >= 0 && id == uint32_t(changedId)) {
3759 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3760 }
3761
3762 pointerCount += 1;
3763 }
3764
3765 ALOG_ASSERT(pointerCount != 0);
3766
3767 if (changedId >= 0 && pointerCount == 1) {
3768 // Replace initial down and final up action.
3769 // We can compare the action without masking off the changed pointer index
3770 // because we know the index is 0.
3771 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3772 action = AMOTION_EVENT_ACTION_DOWN;
3773 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003774 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3775 action = AMOTION_EVENT_ACTION_CANCEL;
3776 } else {
3777 action = AMOTION_EVENT_ACTION_UP;
3778 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003779 } else {
3780 // Can't happen.
3781 ALOG_ASSERT(false);
3782 }
3783 }
3784 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3785 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003786 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003787 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003788 }
3789 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3790 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003791 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003792 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003793 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003794 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3795 policyFlags, action, actionButton, flags, metaState, buttonState,
3796 classification, edgeFlags, pointerCount, pointerProperties,
3797 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3798 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003799}
3800
3801bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3802 const PointerCoords* inCoords,
3803 const uint32_t* inIdToIndex,
3804 PointerProperties* outProperties,
3805 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3806 BitSet32 idBits) const {
3807 bool changed = false;
3808 while (!idBits.isEmpty()) {
3809 uint32_t id = idBits.clearFirstMarkedBit();
3810 uint32_t inIndex = inIdToIndex[id];
3811 uint32_t outIndex = outIdToIndex[id];
3812
3813 const PointerProperties& curInProperties = inProperties[inIndex];
3814 const PointerCoords& curInCoords = inCoords[inIndex];
3815 PointerProperties& curOutProperties = outProperties[outIndex];
3816 PointerCoords& curOutCoords = outCoords[outIndex];
3817
3818 if (curInProperties != curOutProperties) {
3819 curOutProperties.copyFrom(curInProperties);
3820 changed = true;
3821 }
3822
3823 if (curInCoords != curOutCoords) {
3824 curOutCoords.copyFrom(curInCoords);
3825 changed = true;
3826 }
3827 }
3828 return changed;
3829}
3830
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003831std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3832 std::list<NotifyArgs> out;
3833 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3834 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3835 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003836}
3837
Prabir Pradhan1728b212021-10-19 16:00:03 -07003838// Transform input device coordinates to display panel coordinates.
3839void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003840 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3841 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3842
arthurhunga36b28e2020-12-29 20:28:15 +08003843 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3844 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3845
Prabir Pradhan1728b212021-10-19 16:00:03 -07003846 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003847 // 0 - no swap and reverse.
3848 // 90 - swap x/y and reverse y.
3849 // 180 - reverse x, y.
3850 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003851 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003852 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003853 x = xScaled;
3854 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003855 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003856 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003857 y = xScaledMax;
3858 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003859 break;
3860 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003861 x = xScaledMax;
3862 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003863 break;
3864 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003865 y = xScaled;
3866 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003867 break;
3868 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003869 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003870 }
3871}
3872
Prabir Pradhan1728b212021-10-19 16:00:03 -07003873bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003874 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3875 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3876
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003877 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003878 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003879 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003880 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003881}
3882
3883const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3884 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003885 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3886 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3887 "left=%d, top=%d, right=%d, bottom=%d",
3888 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3889 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003890
3891 if (virtualKey.isHit(x, y)) {
3892 return &virtualKey;
3893 }
3894 }
3895
3896 return nullptr;
3897}
3898
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003899void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3900 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3901 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003902
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003903 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003904
3905 if (currentPointerCount == 0) {
3906 // No pointers to assign.
3907 return;
3908 }
3909
3910 if (lastPointerCount == 0) {
3911 // All pointers are new.
3912 for (uint32_t i = 0; i < currentPointerCount; i++) {
3913 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003914 current.rawPointerData.pointers[i].id = id;
3915 current.rawPointerData.idToIndex[id] = i;
3916 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003917 }
3918 return;
3919 }
3920
3921 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003922 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003923 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003924 uint32_t id = last.rawPointerData.pointers[0].id;
3925 current.rawPointerData.pointers[0].id = id;
3926 current.rawPointerData.idToIndex[id] = 0;
3927 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003928 return;
3929 }
3930
3931 // General case.
3932 // We build a heap of squared euclidean distances between current and last pointers
3933 // associated with the current and last pointer indices. Then, we find the best
3934 // match (by distance) for each current pointer.
3935 // The pointers must have the same tool type but it is possible for them to
3936 // transition from hovering to touching or vice-versa while retaining the same id.
3937 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3938
3939 uint32_t heapSize = 0;
3940 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3941 currentPointerIndex++) {
3942 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3943 lastPointerIndex++) {
3944 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003945 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003946 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003947 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003948 if (currentPointer.toolType == lastPointer.toolType) {
3949 int64_t deltaX = currentPointer.x - lastPointer.x;
3950 int64_t deltaY = currentPointer.y - lastPointer.y;
3951
3952 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3953
3954 // Insert new element into the heap (sift up).
3955 heap[heapSize].currentPointerIndex = currentPointerIndex;
3956 heap[heapSize].lastPointerIndex = lastPointerIndex;
3957 heap[heapSize].distance = distance;
3958 heapSize += 1;
3959 }
3960 }
3961 }
3962
3963 // Heapify
3964 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3965 startIndex -= 1;
3966 for (uint32_t parentIndex = startIndex;;) {
3967 uint32_t childIndex = parentIndex * 2 + 1;
3968 if (childIndex >= heapSize) {
3969 break;
3970 }
3971
3972 if (childIndex + 1 < heapSize &&
3973 heap[childIndex + 1].distance < heap[childIndex].distance) {
3974 childIndex += 1;
3975 }
3976
3977 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3978 break;
3979 }
3980
3981 swap(heap[parentIndex], heap[childIndex]);
3982 parentIndex = childIndex;
3983 }
3984 }
3985
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003986 if (DEBUG_POINTER_ASSIGNMENT) {
3987 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3988 for (size_t i = 0; i < heapSize; i++) {
3989 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3990 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3991 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003992 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003993
3994 // Pull matches out by increasing order of distance.
3995 // To avoid reassigning pointers that have already been matched, the loop keeps track
3996 // of which last and current pointers have been matched using the matchedXXXBits variables.
3997 // It also tracks the used pointer id bits.
3998 BitSet32 matchedLastBits(0);
3999 BitSet32 matchedCurrentBits(0);
4000 BitSet32 usedIdBits(0);
4001 bool first = true;
4002 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
4003 while (heapSize > 0) {
4004 if (first) {
4005 // The first time through the loop, we just consume the root element of
4006 // the heap (the one with smallest distance).
4007 first = false;
4008 } else {
4009 // Previous iterations consumed the root element of the heap.
4010 // Pop root element off of the heap (sift down).
4011 heap[0] = heap[heapSize];
4012 for (uint32_t parentIndex = 0;;) {
4013 uint32_t childIndex = parentIndex * 2 + 1;
4014 if (childIndex >= heapSize) {
4015 break;
4016 }
4017
4018 if (childIndex + 1 < heapSize &&
4019 heap[childIndex + 1].distance < heap[childIndex].distance) {
4020 childIndex += 1;
4021 }
4022
4023 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4024 break;
4025 }
4026
4027 swap(heap[parentIndex], heap[childIndex]);
4028 parentIndex = childIndex;
4029 }
4030
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004031 if (DEBUG_POINTER_ASSIGNMENT) {
4032 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4033 for (size_t j = 0; j < heapSize; j++) {
4034 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4035 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4036 heap[j].distance);
4037 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004038 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004039 }
4040
4041 heapSize -= 1;
4042
4043 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4044 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4045
4046 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4047 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4048
4049 matchedCurrentBits.markBit(currentPointerIndex);
4050 matchedLastBits.markBit(lastPointerIndex);
4051
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004052 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4053 current.rawPointerData.pointers[currentPointerIndex].id = id;
4054 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4055 current.rawPointerData.markIdBit(id,
4056 current.rawPointerData.isHovering(
4057 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004058 usedIdBits.markBit(id);
4059
Harry Cutts45483602022-08-24 14:36:48 +00004060 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4061 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4062 ", distance=%" PRIu64,
4063 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004064 break;
4065 }
4066 }
4067
4068 // Assign fresh ids to pointers that were not matched in the process.
4069 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4070 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4071 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4072
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004073 current.rawPointerData.pointers[currentPointerIndex].id = id;
4074 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4075 current.rawPointerData.markIdBit(id,
4076 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004077
Harry Cutts45483602022-08-24 14:36:48 +00004078 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4079 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4080 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004081 }
4082}
4083
4084int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4085 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4086 return AKEY_STATE_VIRTUAL;
4087 }
4088
4089 for (const VirtualKey& virtualKey : mVirtualKeys) {
4090 if (virtualKey.keyCode == keyCode) {
4091 return AKEY_STATE_UP;
4092 }
4093 }
4094
4095 return AKEY_STATE_UNKNOWN;
4096}
4097
4098int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4099 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4100 return AKEY_STATE_VIRTUAL;
4101 }
4102
4103 for (const VirtualKey& virtualKey : mVirtualKeys) {
4104 if (virtualKey.scanCode == scanCode) {
4105 return AKEY_STATE_UP;
4106 }
4107 }
4108
4109 return AKEY_STATE_UNKNOWN;
4110}
4111
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004112bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4113 const std::vector<int32_t>& keyCodes,
4114 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004115 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004116 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004117 if (virtualKey.keyCode == keyCodes[i]) {
4118 outFlags[i] = 1;
4119 }
4120 }
4121 }
4122
4123 return true;
4124}
4125
4126std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4127 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004128 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004129 return std::make_optional(mPointerController->getDisplayId());
4130 } else {
4131 return std::make_optional(mViewport.displayId);
4132 }
4133 }
4134 return std::nullopt;
4135}
4136
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004137} // namespace android