blob: 615889ebe398884688b5e207cbffa8ca717621cd [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 Pradhanbaa5c822019-08-30 15:27:05 -0700173 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100174 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700175 mDisplayWidth(-1),
176 mDisplayHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700177 mPhysicalWidth(-1),
178 mPhysicalHeight(-1),
179 mPhysicalLeft(0),
180 mPhysicalTop(0),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700181 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700182
183TouchInputMapper::~TouchInputMapper() {}
184
Philip Junker4af3b3d2021-12-14 10:36:55 +0100185uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700186 return mSource;
187}
188
189void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
190 InputMapper::populateDeviceInfo(info);
191
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000192 if (mDeviceMode == DeviceMode::DISABLED) {
193 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700194 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000195
196 info->addMotionRange(mOrientedRanges.x);
197 info->addMotionRange(mOrientedRanges.y);
198 info->addMotionRange(mOrientedRanges.pressure);
199
200 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
201 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
202 //
203 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
204 // motion, i.e. the hardware dimensions, as the finger could move completely across the
205 // touchpad in one sample cycle.
206 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
207 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
208 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
209 x.resolution);
210 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
211 y.resolution);
212 }
213
214 if (mOrientedRanges.size) {
215 info->addMotionRange(*mOrientedRanges.size);
216 }
217
218 if (mOrientedRanges.touchMajor) {
219 info->addMotionRange(*mOrientedRanges.touchMajor);
220 info->addMotionRange(*mOrientedRanges.touchMinor);
221 }
222
223 if (mOrientedRanges.toolMajor) {
224 info->addMotionRange(*mOrientedRanges.toolMajor);
225 info->addMotionRange(*mOrientedRanges.toolMinor);
226 }
227
228 if (mOrientedRanges.orientation) {
229 info->addMotionRange(*mOrientedRanges.orientation);
230 }
231
232 if (mOrientedRanges.distance) {
233 info->addMotionRange(*mOrientedRanges.distance);
234 }
235
236 if (mOrientedRanges.tilt) {
237 info->addMotionRange(*mOrientedRanges.tilt);
238 }
239
240 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
241 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
242 }
243 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
244 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
245 }
246 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
247 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
248 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
249 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
250 x.resolution);
251 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
252 y.resolution);
253 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
254 x.resolution);
255 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
256 y.resolution);
257 }
258 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000259 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700260}
261
262void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700263 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800264 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700265 dumpParameters(dump);
266 dumpVirtualKeys(dump);
267 dumpRawPointerAxes(dump);
268 dumpCalibration(dump);
269 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700270 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700271
272 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700273 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
274 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
275 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
276 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
277 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
278 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
279 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
280 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
281 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
282 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
283 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
284 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
285 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
286 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
287
288 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
289 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
290 mLastRawState.rawPointerData.pointerCount);
291 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
292 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
293 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
294 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
295 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
296 "toolType=%d, isHovering=%s\n",
297 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
298 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
299 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
300 pointer.distance, pointer.toolType, toString(pointer.isHovering));
301 }
302
303 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
304 mLastCookedState.buttonState);
305 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
306 mLastCookedState.cookedPointerData.pointerCount);
307 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
308 const PointerProperties& pointerProperties =
309 mLastCookedState.cookedPointerData.pointerProperties[i];
310 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000311 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
312 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
313 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
315 "toolType=%d, isHovering=%s\n",
316 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
327 pointerProperties.toolType,
328 toString(mLastCookedState.cookedPointerData.isHovering(i)));
329 }
330
331 dump += INDENT3 "Stylus Fusion:\n";
332 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
333 toString(mExternalStylusConnected));
334 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
335 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
336 mExternalStylusFusionTimeout);
337 dump += INDENT3 "External Stylus State:\n";
338 dumpStylusState(dump, mExternalStylusState);
339
Michael Wright227c5542020-07-02 18:30:52 +0100340 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
342 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
343 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
344 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
345 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
346 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
347 }
348}
349
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700350std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
351 const InputReaderConfiguration* config,
352 uint32_t changes) {
353 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700354
355 mConfig = *config;
356
357 if (!changes) { // first time only
358 // Configure basic parameters.
359 configureParameters();
360
361 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800362 mCursorScrollAccumulator.configure(getDeviceContext());
363 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364
365 // Configure absolute axis information.
366 configureRawPointerAxes();
367
368 // Prepare input device calibration.
369 parseCalibration();
370 resolveCalibration();
371 }
372
373 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
374 // Update location calibration to reflect current settings
375 updateAffineTransformation();
376 }
377
378 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
379 // Update pointer speed.
380 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
381 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
383 }
384
385 bool resetNeeded = false;
386 if (!changes ||
387 (changes &
388 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800389 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
391 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
392 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700393 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700394 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700395 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700396 }
397
398 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700399 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000400
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700401 // Send reset, unless this is the first time the device has been configured,
402 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000403 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700404 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700405 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700406}
407
408void TouchInputMapper::resolveExternalStylusPresence() {
409 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800410 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700411 mExternalStylusConnected = !devices.empty();
412
413 if (!mExternalStylusConnected) {
414 resetExternalStylus();
415 }
416}
417
418void TouchInputMapper::configureParameters() {
419 // Use the pointer presentation mode for devices that do not support distinct
420 // multitouch. The spot-based presentation relies on being able to accurately
421 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800422 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100423 ? Parameters::GestureMode::SINGLE_TOUCH
424 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700425
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700426 std::string gestureModeString;
427 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800428 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700429 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100430 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700431 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100432 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700433 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700434 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700435 }
436 }
437
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800438 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800441 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700442 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100443 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444 } else {
445 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100446 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447 }
448
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800449 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700451 std::string deviceTypeString;
452 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800453 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700454 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100455 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700461 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462 }
463 }
464
Michael Wright227c5542020-07-02 18:30:52 +0100465 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700466 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800467 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700468
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700469 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700470 std::string orientationString;
471 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700472 orientationString)) {
473 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
474 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
475 } else if (orientationString == "ORIENTATION_90") {
476 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
477 } else if (orientationString == "ORIENTATION_180") {
478 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
479 } else if (orientationString == "ORIENTATION_270") {
480 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
481 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700482 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700483 }
484 }
485
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700486 mParameters.hasAssociatedDisplay = false;
487 mParameters.associatedDisplayIsExternal = false;
488 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100489 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
490 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700491 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100492 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800493 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700494 std::string uniqueDisplayId;
495 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800496 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700497 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
498 }
499 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800500 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700501 mParameters.hasAssociatedDisplay = true;
502 }
503
504 // Initial downs on external touch devices should wake the device.
505 // Normally we don't do this for internal touch screens to prevent them from waking
506 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800507 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700508 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000509
510 mParameters.supportsUsi = false;
511 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
512 mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700513}
514
515void TouchInputMapper::dumpParameters(std::string& dump) {
516 dump += INDENT3 "Parameters:\n";
517
Dominik Laskowski75788452021-02-09 18:51:25 -0800518 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700519
Dominik Laskowski75788452021-02-09 18:51:25 -0800520 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700521
522 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
523 "displayId='%s'\n",
524 toString(mParameters.hasAssociatedDisplay),
525 toString(mParameters.associatedDisplayIsExternal),
526 mParameters.uniqueDisplayId.c_str());
527 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800528 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000529 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700530}
531
532void TouchInputMapper::configureRawPointerAxes() {
533 mRawPointerAxes.clear();
534}
535
536void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
537 dump += INDENT3 "Raw Touch Axes:\n";
538 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
549 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
550 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
551}
552
553bool TouchInputMapper::hasExternalStylus() const {
554 return mExternalStylusConnected;
555}
556
557/**
558 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000559 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800560 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000561 * 3. Get the matching viewport by either unique id in idc file or by the display type
562 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800563 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 */
565std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800566 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000567 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800568 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700569 }
570
Christine Franks2a2293c2022-01-18 11:51:16 -0800571 const std::optional<std::string> associatedDisplayUniqueId =
572 getDeviceContext().getAssociatedDisplayUniqueId();
573 if (associatedDisplayUniqueId) {
574 return getDeviceContext().getAssociatedViewport();
575 }
576
Michael Wright227c5542020-07-02 18:30:52 +0100577 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800578 std::optional<DisplayViewport> viewport =
579 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
580 if (viewport) {
581 return viewport;
582 } else {
583 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
584 mConfig.defaultPointerDisplayId);
585 }
586 }
587
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700588 // Check if uniqueDisplayId is specified in idc file.
589 if (!mParameters.uniqueDisplayId.empty()) {
590 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
591 }
592
593 ViewportType viewportTypeToUse;
594 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100595 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700596 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100597 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700598 }
599
600 std::optional<DisplayViewport> viewport =
601 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100602 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700603 ALOGW("Input device %s should be associated with external display, "
604 "fallback to internal one for the external viewport is not found.",
605 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100606 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700607 }
608
609 return viewport;
610 }
611
612 // No associated display, return a non-display viewport.
613 DisplayViewport newViewport;
614 // Raw width and height in the natural orientation.
615 int32_t rawWidth = mRawPointerAxes.getRawWidth();
616 int32_t rawHeight = mRawPointerAxes.getRawHeight();
617 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
618 return std::make_optional(newViewport);
619}
620
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800621int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
622 if (resolution < 0) {
623 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
624 getDeviceName().c_str());
625 return 0;
626 }
627 return resolution;
628}
629
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800630void TouchInputMapper::initializeSizeRanges() {
631 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
632 mSizeScale = 0.0f;
633 return;
634 }
635
636 // Size of diagonal axis.
637 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
638
639 // Size factors.
640 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
641 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
642 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
643 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
644 } else {
645 mSizeScale = 0.0f;
646 }
647
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700648 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
649 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
650 .source = mSource,
651 .min = 0,
652 .max = diagonalSize,
653 .flat = 0,
654 .fuzz = 0,
655 .resolution = 0,
656 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800657
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800658 if (mRawPointerAxes.touchMajor.valid) {
659 mRawPointerAxes.touchMajor.resolution =
660 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700661 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800662 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800663
664 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700665 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800666 if (mRawPointerAxes.touchMinor.valid) {
667 mRawPointerAxes.touchMinor.resolution =
668 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700669 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800670 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800671
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700672 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
673 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
674 .source = mSource,
675 .min = 0,
676 .max = diagonalSize,
677 .flat = 0,
678 .fuzz = 0,
679 .resolution = 0,
680 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800681 if (mRawPointerAxes.toolMajor.valid) {
682 mRawPointerAxes.toolMajor.resolution =
683 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700684 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800685 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800686
687 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700688 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800689 if (mRawPointerAxes.toolMinor.valid) {
690 mRawPointerAxes.toolMinor.resolution =
691 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700692 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800693 }
694
695 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700696 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
697 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
698 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
699 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800700 } else {
701 // Support for other calibrations can be added here.
702 ALOGW("%s calibration is not supported for size ranges at the moment. "
703 "Using raw resolution instead",
704 ftl::enum_string(mCalibration.sizeCalibration).c_str());
705 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800706
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700707 mOrientedRanges.size = InputDeviceInfo::MotionRange{
708 .axis = AMOTION_EVENT_AXIS_SIZE,
709 .source = mSource,
710 .min = 0,
711 .max = 1.0,
712 .flat = 0,
713 .fuzz = 0,
714 .resolution = 0,
715 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800716}
717
718void TouchInputMapper::initializeOrientedRanges() {
719 // Configure X and Y factors.
720 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
721 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
722 mXPrecision = 1.0f / mXScale;
723 mYPrecision = 1.0f / mYScale;
724
725 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
726 mOrientedRanges.x.source = mSource;
727 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
728 mOrientedRanges.y.source = mSource;
729
730 // Scale factor for terms that are not oriented in a particular axis.
731 // If the pixels are square then xScale == yScale otherwise we fake it
732 // by choosing an average.
733 mGeometricScale = avg(mXScale, mYScale);
734
735 initializeSizeRanges();
736
737 // Pressure factors.
738 mPressureScale = 0;
739 float pressureMax = 1.0;
740 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
741 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700742 if (mCalibration.pressureScale) {
743 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800744 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
745 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
746 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
747 }
748 }
749
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700750 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
751 .axis = AMOTION_EVENT_AXIS_PRESSURE,
752 .source = mSource,
753 .min = 0,
754 .max = pressureMax,
755 .flat = 0,
756 .fuzz = 0,
757 .resolution = 0,
758 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800759
760 // Tilt
761 mTiltXCenter = 0;
762 mTiltXScale = 0;
763 mTiltYCenter = 0;
764 mTiltYScale = 0;
765 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
766 if (mHaveTilt) {
767 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
768 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
769 mTiltXScale = M_PI / 180;
770 mTiltYScale = M_PI / 180;
771
772 if (mRawPointerAxes.tiltX.resolution) {
773 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
774 }
775 if (mRawPointerAxes.tiltY.resolution) {
776 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
777 }
778
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700779 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
780 .axis = AMOTION_EVENT_AXIS_TILT,
781 .source = mSource,
782 .min = 0,
783 .max = M_PI_2,
784 .flat = 0,
785 .fuzz = 0,
786 .resolution = 0,
787 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800788 }
789
790 // Orientation
791 mOrientationScale = 0;
792 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700793 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
794 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
795 .source = mSource,
796 .min = -M_PI,
797 .max = M_PI,
798 .flat = 0,
799 .fuzz = 0,
800 .resolution = 0,
801 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800802
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800803 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
804 if (mCalibration.orientationCalibration ==
805 Calibration::OrientationCalibration::INTERPOLATED) {
806 if (mRawPointerAxes.orientation.valid) {
807 if (mRawPointerAxes.orientation.maxValue > 0) {
808 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
809 } else if (mRawPointerAxes.orientation.minValue < 0) {
810 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
811 } else {
812 mOrientationScale = 0;
813 }
814 }
815 }
816
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700817 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
818 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
819 .source = mSource,
820 .min = -M_PI_2,
821 .max = M_PI_2,
822 .flat = 0,
823 .fuzz = 0,
824 .resolution = 0,
825 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800826 }
827
828 // Distance
829 mDistanceScale = 0;
830 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
831 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700832 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800833 }
834
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700835 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800836
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700837 .axis = AMOTION_EVENT_AXIS_DISTANCE,
838 .source = mSource,
839 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
840 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
841 .flat = 0,
842 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
843 .resolution = 0,
844 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800845 }
846
847 // Compute oriented precision, scales and ranges.
848 // Note that the maximum value reported is an inclusive maximum value so it is one
849 // unit less than the total width or height of the display.
850 switch (mInputDeviceOrientation) {
851 case DISPLAY_ORIENTATION_90:
852 case DISPLAY_ORIENTATION_270:
853 mOrientedXPrecision = mYPrecision;
854 mOrientedYPrecision = mXPrecision;
855
856 mOrientedRanges.x.min = 0;
857 mOrientedRanges.x.max = mDisplayHeight - 1;
858 mOrientedRanges.x.flat = 0;
859 mOrientedRanges.x.fuzz = 0;
860 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
861
862 mOrientedRanges.y.min = 0;
863 mOrientedRanges.y.max = mDisplayWidth - 1;
864 mOrientedRanges.y.flat = 0;
865 mOrientedRanges.y.fuzz = 0;
866 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
867 break;
868
869 default:
870 mOrientedXPrecision = mXPrecision;
871 mOrientedYPrecision = mYPrecision;
872
873 mOrientedRanges.x.min = 0;
874 mOrientedRanges.x.max = mDisplayWidth - 1;
875 mOrientedRanges.x.flat = 0;
876 mOrientedRanges.x.fuzz = 0;
877 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
878
879 mOrientedRanges.y.min = 0;
880 mOrientedRanges.y.max = mDisplayHeight - 1;
881 mOrientedRanges.y.flat = 0;
882 mOrientedRanges.y.fuzz = 0;
883 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
884 break;
885 }
886}
887
Prabir Pradhan1728b212021-10-19 16:00:03 -0700888void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000889 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700890
891 resolveExternalStylusPresence();
892
893 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100894 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000895 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700896 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100897 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700898 if (hasStylus()) {
899 mSource |= AINPUT_SOURCE_STYLUS;
900 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800901 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100903 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 if (hasStylus()) {
905 mSource |= AINPUT_SOURCE_STYLUS;
906 }
907 if (hasExternalStylus()) {
908 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
909 }
Michael Wright227c5542020-07-02 18:30:52 +0100910 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100912 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700913 } else {
914 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100915 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700916 }
917
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000918 const std::optional<DisplayViewport> newViewportOpt = findViewport();
919
920 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700921 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
922 ALOGW("Touch device '%s' did not report support for X or Y axis! "
923 "The device will be inoperable.",
924 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100925 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000926 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700927 ALOGI("Touch device '%s' could not query the properties of its associated "
928 "display. The device will be inoperable until the display size "
929 "becomes available.",
930 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100931 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000932 } else if (!newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000933 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
934 getDeviceName().c_str(), getDeviceId());
935 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000936 }
937
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700938 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700939 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
940 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000941 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
942 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
943 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
944 const float rawMeanResolution =
945 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700946
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000947 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
948 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700949 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700950 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000951 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
952 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
953 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700954
Michael Wright227c5542020-07-02 18:30:52 +0100955 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700956 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700957 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
958 int32_t naturalPhysicalLeft, naturalPhysicalTop;
959 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700960
Prabir Pradhan1728b212021-10-19 16:00:03 -0700961 // Apply the inverse of the input device orientation so that the input device is
962 // configured in the same orientation as the viewport. The input device orientation will
963 // be re-applied by mInputDeviceOrientation.
964 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700965 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700966 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700967 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700968 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
969 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800970 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700971 naturalPhysicalTop = mViewport.physicalLeft;
972 naturalDeviceWidth = mViewport.deviceHeight;
973 naturalDeviceHeight = mViewport.deviceWidth;
974 break;
975 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700976 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
977 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
978 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
979 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
980 naturalDeviceWidth = mViewport.deviceWidth;
981 naturalDeviceHeight = mViewport.deviceHeight;
982 break;
983 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700984 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
985 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
986 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800987 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700988 naturalDeviceWidth = mViewport.deviceHeight;
989 naturalDeviceHeight = mViewport.deviceWidth;
990 break;
991 case DISPLAY_ORIENTATION_0:
992 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700993 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
994 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
995 naturalPhysicalLeft = mViewport.physicalLeft;
996 naturalPhysicalTop = mViewport.physicalTop;
997 naturalDeviceWidth = mViewport.deviceWidth;
998 naturalDeviceHeight = mViewport.deviceHeight;
999 break;
1000 }
1001
1002 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
1003 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
1004 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
1005 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
1006 }
1007
1008 mPhysicalWidth = naturalPhysicalWidth;
1009 mPhysicalHeight = naturalPhysicalHeight;
1010 mPhysicalLeft = naturalPhysicalLeft;
1011 mPhysicalTop = naturalPhysicalTop;
1012
Prabir Pradhan1728b212021-10-19 16:00:03 -07001013 const int32_t oldDisplayWidth = mDisplayWidth;
1014 const int32_t oldDisplayHeight = mDisplayHeight;
1015 mDisplayWidth = naturalDeviceWidth;
1016 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -07001017
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001018 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1019 // anything if the device is already orientation-aware. If the device is not
1020 // orientation-aware, then we need to apply the inverse rotation of the display so that
1021 // when the display rotation is applied later as a part of the per-window transform, we
1022 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001023 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001024 ? DISPLAY_ORIENTATION_0
1025 : getInverseRotation(mViewport.orientation);
1026 // For orientation-aware devices that work in the un-rotated coordinate space, the
1027 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001028 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
1029 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
1030 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001031
1032 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001033 mInputDeviceOrientation =
1034 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035 } else {
1036 mPhysicalWidth = rawWidth;
1037 mPhysicalHeight = rawHeight;
1038 mPhysicalLeft = 0;
1039 mPhysicalTop = 0;
1040
Prabir Pradhan1728b212021-10-19 16:00:03 -07001041 mDisplayWidth = rawWidth;
1042 mDisplayHeight = rawHeight;
1043 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001044 }
1045 }
1046
1047 // If moving between pointer modes, need to reset some state.
1048 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1049 if (deviceModeChanged) {
1050 mOrientedRanges.clear();
1051 }
1052
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001053 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
1054 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +01001055 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001056 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001057 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1058 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001059 if (mPointerController == nullptr) {
1060 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001061 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001062 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001063 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1064 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001065 } else {
lilinnandef700b2022-06-17 19:32:01 +08001066 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1067 !mConfig.showTouches) {
1068 mPointerController->clearSpots();
1069 }
Michael Wright17db18e2020-06-26 20:51:44 +01001070 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001071 }
1072
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001073 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001074 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1075 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001076 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1077 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001078
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001079 configureVirtualKeys();
1080
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001081 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082
1083 // Location
1084 updateAffineTransformation();
1085
Michael Wright227c5542020-07-02 18:30:52 +01001086 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001087 // Compute pointer gesture detection parameters.
1088 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001089 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001090
1091 // Scale movements such that one whole swipe of the touch pad covers a
1092 // given area relative to the diagonal size of the display when no acceleration
1093 // is applied.
1094 // Assume that the touch pad has a square aspect ratio such that movements in
1095 // X and Y of the same number of raw units cover the same physical distance.
1096 mPointerXMovementScale =
1097 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1098 mPointerYMovementScale = mPointerXMovementScale;
1099
1100 // Scale zooms to cover a smaller range of the display than movements do.
1101 // This value determines the area around the pointer that is affected by freeform
1102 // pointer gestures.
1103 mPointerXZoomScale =
1104 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1105 mPointerYZoomScale = mPointerXZoomScale;
1106
HQ Liue6983c72022-04-19 22:14:56 +00001107 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1108 // axis is non positive value.
1109 const float minFreeformGestureWidth =
1110 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1111
1112 mPointerGestureMaxSwipeWidth =
1113 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1114 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001115 }
1116
1117 // Inform the dispatcher about the changes.
1118 *outResetNeeded = true;
1119 bumpGeneration();
1120 }
1121}
1122
Prabir Pradhan1728b212021-10-19 16:00:03 -07001123void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001124 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001125 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1126 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001127 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1128 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1129 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1130 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001131 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132}
1133
1134void TouchInputMapper::configureVirtualKeys() {
1135 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001136 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137
1138 mVirtualKeys.clear();
1139
1140 if (virtualKeyDefinitions.size() == 0) {
1141 return;
1142 }
1143
1144 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1145 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1146 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1147 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1148
1149 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1150 VirtualKey virtualKey;
1151
1152 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1153 int32_t keyCode;
1154 int32_t dummyKeyMetaState;
1155 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001156 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1157 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001158 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1159 continue; // drop the key
1160 }
1161
1162 virtualKey.keyCode = keyCode;
1163 virtualKey.flags = flags;
1164
1165 // convert the key definition's display coordinates into touch coordinates for a hit box
1166 int32_t halfWidth = virtualKeyDefinition.width / 2;
1167 int32_t halfHeight = virtualKeyDefinition.height / 2;
1168
1169 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001170 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 touchScreenLeft;
1172 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001173 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001175 virtualKey.hitTop =
1176 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001178 virtualKey.hitBottom =
1179 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 touchScreenTop;
1181 mVirtualKeys.push_back(virtualKey);
1182 }
1183}
1184
1185void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1186 if (!mVirtualKeys.empty()) {
1187 dump += INDENT3 "Virtual Keys:\n";
1188
1189 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1190 const VirtualKey& virtualKey = mVirtualKeys[i];
1191 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1192 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1193 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1194 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1195 }
1196 }
1197}
1198
1199void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001200 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 Calibration& out = mCalibration;
1202
1203 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001205 std::string sizeCalibrationString;
1206 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001214 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001218 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 }
1220 }
1221
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001222 float sizeScale;
1223
1224 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1225 out.sizeScale = sizeScale;
1226 }
1227 float sizeBias;
1228 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1229 out.sizeBias = sizeBias;
1230 }
1231 bool sizeIsSummed;
1232 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1233 out.sizeIsSummed = sizeIsSummed;
1234 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235
1236 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001237 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001238 std::string pressureCalibrationString;
1239 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001241 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001243 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001245 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 } else if (pressureCalibrationString != "default") {
1247 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001248 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250 }
1251
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001252 float pressureScale;
1253 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1254 out.pressureScale = pressureScale;
1255 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256
1257 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001258 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001259 std::string orientationCalibrationString;
1260 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001262 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001264 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001266 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 } else if (orientationCalibrationString != "default") {
1268 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001269 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270 }
1271 }
1272
1273 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001274 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001275 std::string distanceCalibrationString;
1276 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001278 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001280 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 } else if (distanceCalibrationString != "default") {
1282 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001283 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285 }
1286
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001287 float distanceScale;
1288 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1289 out.distanceScale = distanceScale;
1290 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291
Michael Wright227c5542020-07-02 18:30:52 +01001292 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001293 std::string coverageCalibrationString;
1294 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001296 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001298 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 } else if (coverageCalibrationString != "default") {
1300 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001301 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001302 }
1303 }
1304}
1305
1306void TouchInputMapper::resolveCalibration() {
1307 // Size
1308 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001309 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1310 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 }
1312 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001313 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314 }
1315
1316 // Pressure
1317 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001318 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1319 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 }
1321 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001322 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001323 }
1324
1325 // Orientation
1326 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001327 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1328 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 }
1330 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001331 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 }
1333
1334 // Distance
1335 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001336 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1337 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 }
1339 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001340 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 }
1342
1343 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001344 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1345 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 }
1347}
1348
1349void TouchInputMapper::dumpCalibration(std::string& dump) {
1350 dump += INDENT3 "Calibration:\n";
1351
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001352 dump += INDENT4 "touch.size.calibration: ";
1353 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001354
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001355 if (mCalibration.sizeScale) {
1356 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 }
1358
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001359 if (mCalibration.sizeBias) {
1360 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361 }
1362
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001363 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001364 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001365 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366 }
1367
1368 // Pressure
1369 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001370 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001371 dump += INDENT4 "touch.pressure.calibration: none\n";
1372 break;
Michael Wright227c5542020-07-02 18:30:52 +01001373 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374 dump += INDENT4 "touch.pressure.calibration: physical\n";
1375 break;
Michael Wright227c5542020-07-02 18:30:52 +01001376 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001377 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1378 break;
1379 default:
1380 ALOG_ASSERT(false);
1381 }
1382
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001383 if (mCalibration.pressureScale) {
1384 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001385 }
1386
1387 // Orientation
1388 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001389 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001390 dump += INDENT4 "touch.orientation.calibration: none\n";
1391 break;
Michael Wright227c5542020-07-02 18:30:52 +01001392 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001393 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1394 break;
Michael Wright227c5542020-07-02 18:30:52 +01001395 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001396 dump += INDENT4 "touch.orientation.calibration: vector\n";
1397 break;
1398 default:
1399 ALOG_ASSERT(false);
1400 }
1401
1402 // Distance
1403 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001404 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001405 dump += INDENT4 "touch.distance.calibration: none\n";
1406 break;
Michael Wright227c5542020-07-02 18:30:52 +01001407 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001408 dump += INDENT4 "touch.distance.calibration: scaled\n";
1409 break;
1410 default:
1411 ALOG_ASSERT(false);
1412 }
1413
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001414 if (mCalibration.distanceScale) {
1415 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001416 }
1417
1418 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001419 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001420 dump += INDENT4 "touch.coverage.calibration: none\n";
1421 break;
Michael Wright227c5542020-07-02 18:30:52 +01001422 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423 dump += INDENT4 "touch.coverage.calibration: box\n";
1424 break;
1425 default:
1426 ALOG_ASSERT(false);
1427 }
1428}
1429
1430void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1431 dump += INDENT3 "Affine Transformation:\n";
1432
1433 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1434 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1435 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1436 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1437 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1438 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1439}
1440
1441void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001442 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001443 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444}
1445
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001446std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001447 std::list<NotifyArgs> out = cancelTouch(when, when);
1448 updateTouchSpots();
1449
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001450 mCursorButtonAccumulator.reset(getDeviceContext());
1451 mCursorScrollAccumulator.reset(getDeviceContext());
1452 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001453
1454 mPointerVelocityControl.reset();
1455 mWheelXVelocityControl.reset();
1456 mWheelYVelocityControl.reset();
1457
1458 mRawStatesPending.clear();
1459 mCurrentRawState.clear();
1460 mCurrentCookedState.clear();
1461 mLastRawState.clear();
1462 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001463 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001464 mSentHoverEnter = false;
1465 mHavePointerIds = false;
1466 mCurrentMotionAborted = false;
1467 mDownTime = 0;
1468
1469 mCurrentVirtualKey.down = false;
1470
1471 mPointerGesture.reset();
1472 mPointerSimple.reset();
1473 resetExternalStylus();
1474
1475 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001476 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001477 mPointerController->clearSpots();
1478 }
1479
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001480 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001481}
1482
1483void TouchInputMapper::resetExternalStylus() {
1484 mExternalStylusState.clear();
1485 mExternalStylusId = -1;
1486 mExternalStylusFusionTimeout = LLONG_MAX;
1487 mExternalStylusDataPending = false;
1488}
1489
1490void TouchInputMapper::clearStylusDataPendingFlags() {
1491 mExternalStylusDataPending = false;
1492 mExternalStylusFusionTimeout = LLONG_MAX;
1493}
1494
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001495std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496 mCursorButtonAccumulator.process(rawEvent);
1497 mCursorScrollAccumulator.process(rawEvent);
1498 mTouchButtonAccumulator.process(rawEvent);
1499
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001500 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001501 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001502 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001503 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001504 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001505}
1506
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001507std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1508 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001509 if (mDeviceMode == DeviceMode::DISABLED) {
1510 // Only save the last pending state when the device is disabled.
1511 mRawStatesPending.clear();
1512 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001513 // Push a new state.
1514 mRawStatesPending.emplace_back();
1515
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001516 RawState& next = mRawStatesPending.back();
1517 next.clear();
1518 next.when = when;
1519 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001520
1521 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001522 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001523 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1524
1525 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001526 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1527 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001528 mCursorScrollAccumulator.finishSync();
1529
1530 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001531 syncTouch(when, &next);
1532
1533 // The last RawState is the actually second to last, since we just added a new state
1534 const RawState& last =
1535 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001536
1537 // Assign pointer ids.
1538 if (!mHavePointerIds) {
1539 assignPointerIds(last, next);
1540 }
1541
Harry Cutts45483602022-08-24 14:36:48 +00001542 ALOGD_IF(DEBUG_RAW_EVENTS,
1543 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1544 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1545 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1546 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1547 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1548 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001549
Arthur Hung9ad18942021-06-19 02:04:46 +00001550 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1551 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1552 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1553 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1554 next.rawPointerData.hoveringIdBits.value);
1555 }
1556
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001557 out += processRawTouches(false /*timeout*/);
1558 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001559}
1560
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001561std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1562 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001563 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001564 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001565 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001566 }
1567
1568 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1569 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1570 // touching the current state will only observe the events that have been dispatched to the
1571 // rest of the pipeline.
1572 const size_t N = mRawStatesPending.size();
1573 size_t count;
1574 for (count = 0; count < N; count++) {
1575 const RawState& next = mRawStatesPending[count];
1576
1577 // A failure to assign the stylus id means that we're waiting on stylus data
1578 // and so should defer the rest of the pipeline.
1579 if (assignExternalStylusId(next, timeout)) {
1580 break;
1581 }
1582
1583 // All ready to go.
1584 clearStylusDataPendingFlags();
1585 mCurrentRawState.copyFrom(next);
1586 if (mCurrentRawState.when < mLastRawState.when) {
1587 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001588 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001589 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001590 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 }
1592 if (count != 0) {
1593 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1594 }
1595
1596 if (mExternalStylusDataPending) {
1597 if (timeout) {
1598 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1599 clearStylusDataPendingFlags();
1600 mCurrentRawState.copyFrom(mLastRawState);
Harry Cutts45483602022-08-24 14:36:48 +00001601 ALOGD_IF(DEBUG_STYLUS_FUSION,
1602 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001603 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001604 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001605 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1606 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1607 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1608 }
1609 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001610 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001611}
1612
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001613std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1614 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 // Always start with a clean state.
1616 mCurrentCookedState.clear();
1617
1618 // Apply stylus buttons to current raw state.
1619 applyExternalStylusButtonState(when);
1620
1621 // Handle policy on initial down or hover events.
1622 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1623 mCurrentRawState.rawPointerData.pointerCount != 0;
1624
1625 uint32_t policyFlags = 0;
1626 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1627 if (initialDown || buttonsPressed) {
1628 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001629 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 getContext()->fadePointer();
1631 }
1632
1633 if (mParameters.wake) {
1634 policyFlags |= POLICY_FLAG_WAKE;
1635 }
1636 }
1637
1638 // Consume raw off-screen touches before cooking pointer data.
1639 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001640 bool consumed;
1641 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1642 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001643 mCurrentRawState.rawPointerData.clear();
1644 }
1645
1646 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1647 // with cooked pointer data that has the same ids and indices as the raw data.
1648 // The following code can use either the raw or cooked data, as needed.
1649 cookPointerData();
1650
1651 // Apply stylus pressure to current cooked state.
1652 applyExternalStylusTouchState(when);
1653
1654 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001655 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1656 mSource, mViewport.displayId, policyFlags,
1657 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001658
1659 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001660 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001661 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1662 uint32_t id = idBits.clearFirstMarkedBit();
1663 const RawPointerData::Pointer& pointer =
1664 mCurrentRawState.rawPointerData.pointerForId(id);
1665 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1666 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1667 mCurrentCookedState.stylusIdBits.markBit(id);
1668 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1669 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1670 mCurrentCookedState.fingerIdBits.markBit(id);
1671 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1672 mCurrentCookedState.mouseIdBits.markBit(id);
1673 }
1674 }
1675 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1676 uint32_t id = idBits.clearFirstMarkedBit();
1677 const RawPointerData::Pointer& pointer =
1678 mCurrentRawState.rawPointerData.pointerForId(id);
1679 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1680 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1681 mCurrentCookedState.stylusIdBits.markBit(id);
1682 }
1683 }
1684
1685 // Stylus takes precedence over all tools, then mouse, then finger.
1686 PointerUsage pointerUsage = mPointerUsage;
1687 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1688 mCurrentCookedState.mouseIdBits.clear();
1689 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001690 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001691 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1692 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001693 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001694 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1695 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001696 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001697 }
1698
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001699 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001700 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001701 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001702 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001703 out += dispatchButtonRelease(when, readTime, policyFlags);
1704 out += dispatchHoverExit(when, readTime, policyFlags);
1705 out += dispatchTouches(when, readTime, policyFlags);
1706 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1707 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001708 }
1709
1710 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1711 mCurrentMotionAborted = false;
1712 }
1713 }
1714
1715 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001716 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1717 mSource, mViewport.displayId, policyFlags,
1718 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001719
1720 // Clear some transient state.
1721 mCurrentRawState.rawVScroll = 0;
1722 mCurrentRawState.rawHScroll = 0;
1723
1724 // Copy current touch to last touch in preparation for the next cycle.
1725 mLastRawState.copyFrom(mCurrentRawState);
1726 mLastCookedState.copyFrom(mCurrentCookedState);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001727 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001728}
1729
Garfield Tanc734e4f2021-01-15 20:01:39 -08001730void TouchInputMapper::updateTouchSpots() {
1731 if (!mConfig.showTouches || mPointerController == nullptr) {
1732 return;
1733 }
1734
1735 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1736 // clear touch spots.
1737 if (mDeviceMode != DeviceMode::DIRECT &&
1738 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1739 return;
1740 }
1741
1742 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1743 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1744
1745 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001746 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1747 mCurrentCookedState.cookedPointerData.idToIndex,
1748 mCurrentCookedState.cookedPointerData.touchingIdBits,
1749 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001750}
1751
1752bool TouchInputMapper::isTouchScreen() {
1753 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1754 mParameters.hasAssociatedDisplay;
1755}
1756
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001757void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001758 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001759 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1760 }
1761}
1762
1763void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1764 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1765 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1766
1767 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1768 float pressure = mExternalStylusState.pressure;
1769 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1770 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1771 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1772 }
1773 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1774 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1775
1776 PointerProperties& properties =
1777 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1778 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1779 properties.toolType = mExternalStylusState.toolType;
1780 }
1781 }
1782}
1783
1784bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001785 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001786 return false;
1787 }
1788
1789 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1790 state.rawPointerData.pointerCount != 0;
1791 if (initialDown) {
1792 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001793 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001794 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1795 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001796 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001797 resetExternalStylus();
1798 } else {
1799 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1800 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1801 }
Harry Cutts45483602022-08-24 14:36:48 +00001802 ALOGD_IF(DEBUG_STYLUS_FUSION,
1803 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1804 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001805 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1806 return true;
1807 }
1808 }
1809
1810 // Check if the stylus pointer has gone up.
1811 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001812 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001813 mExternalStylusId = -1;
1814 }
1815
1816 return false;
1817}
1818
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001819std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1820 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001821 if (mDeviceMode == DeviceMode::POINTER) {
1822 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001823 // Since this is a synthetic event, we can consider its latency to be zero
1824 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001825 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001826 }
Michael Wright227c5542020-07-02 18:30:52 +01001827 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001828 if (mExternalStylusFusionTimeout < when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001829 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001830 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1831 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1832 }
1833 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001834 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001835}
1836
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001837std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1838 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001839 mExternalStylusState.copyFrom(state);
1840 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1841 // We're either in the middle of a fused stream of data or we're waiting on data before
1842 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1843 // data.
1844 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001845 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001847 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001848}
1849
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001850std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1851 uint32_t policyFlags, bool& outConsumed) {
1852 outConsumed = false;
1853 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854 // Check for release of a virtual key.
1855 if (mCurrentVirtualKey.down) {
1856 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1857 // Pointer went up while virtual key was down.
1858 mCurrentVirtualKey.down = false;
1859 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001860 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1861 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1862 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001863 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1864 AKEY_EVENT_FLAG_FROM_SYSTEM |
1865 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001866 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001867 outConsumed = true;
1868 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001869 }
1870
1871 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1872 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1873 const RawPointerData::Pointer& pointer =
1874 mCurrentRawState.rawPointerData.pointerForId(id);
1875 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1876 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1877 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001878 outConsumed = true;
1879 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001880 }
1881 }
1882
1883 // Pointer left virtual key area or another pointer also went down.
1884 // Send key cancellation but do not consume the touch yet.
1885 // This is useful when the user swipes through from the virtual key area
1886 // into the main display surface.
1887 mCurrentVirtualKey.down = false;
1888 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001889 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1890 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001891 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1892 AKEY_EVENT_FLAG_FROM_SYSTEM |
1893 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1894 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001895 }
1896 }
1897
1898 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1899 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1900 // Pointer just went down. Check for virtual key press or off-screen touches.
1901 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1902 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001903 // Skip checking whether the pointer is inside the physical frame if the device is in
1904 // unscaled mode.
1905 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1906 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907 // If exactly one pointer went down, check for virtual key hit.
1908 // Otherwise we will drop the entire stroke.
1909 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1910 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1911 if (virtualKey) {
1912 mCurrentVirtualKey.down = true;
1913 mCurrentVirtualKey.downTime = when;
1914 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1915 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1916 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001917 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1918 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001919
1920 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001921 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1922 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1923 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001924 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1925 AKEY_EVENT_ACTION_DOWN,
1926 AKEY_EVENT_FLAG_FROM_SYSTEM |
1927 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001928 }
1929 }
1930 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001931 outConsumed = true;
1932 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001933 }
1934 }
1935
1936 // Disable all virtual key touches that happen within a short time interval of the
1937 // most recent touch within the screen area. The idea is to filter out stray
1938 // virtual key presses when interacting with the touch screen.
1939 //
1940 // Problems we're trying to solve:
1941 //
1942 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1943 // virtual key area that is implemented by a separate touch panel and accidentally
1944 // triggers a virtual key.
1945 //
1946 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1947 // area and accidentally triggers a virtual key. This often happens when virtual keys
1948 // are layed out below the screen near to where the on screen keyboard's space bar
1949 // is displayed.
1950 if (mConfig.virtualKeyQuietTime > 0 &&
1951 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001952 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001953 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001954 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001955}
1956
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001957NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1958 uint32_t policyFlags, int32_t keyEventAction,
1959 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001960 int32_t keyCode = mCurrentVirtualKey.keyCode;
1961 int32_t scanCode = mCurrentVirtualKey.scanCode;
1962 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001963 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001964 policyFlags |= POLICY_FLAG_VIRTUAL;
1965
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001966 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1967 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1968 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001969}
1970
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001971std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1972 uint32_t policyFlags) {
1973 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001974 if (mCurrentMotionAborted) {
1975 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001976 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001977 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001978 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1979 if (!currentIdBits.isEmpty()) {
1980 int32_t metaState = getContext()->getGlobalMetaState();
1981 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001982 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001983 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1984 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001985 mCurrentCookedState.cookedPointerData.pointerProperties,
1986 mCurrentCookedState.cookedPointerData.pointerCoords,
1987 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1988 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1989 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001990 mCurrentMotionAborted = true;
1991 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001992 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001993}
1994
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001995std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1996 uint32_t policyFlags) {
1997 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001998 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1999 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2000 int32_t metaState = getContext()->getGlobalMetaState();
2001 int32_t buttonState = mCurrentCookedState.buttonState;
2002
2003 if (currentIdBits == lastIdBits) {
2004 if (!currentIdBits.isEmpty()) {
2005 // No pointer id changes so this is a move event.
2006 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002007 out.push_back(
2008 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2009 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2010 mCurrentCookedState.cookedPointerData.pointerProperties,
2011 mCurrentCookedState.cookedPointerData.pointerCoords,
2012 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2013 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2014 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002015 }
2016 } else {
2017 // There may be pointers going up and pointers going down and pointers moving
2018 // all at the same time.
2019 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2020 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2021 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2022 BitSet32 dispatchedIdBits(lastIdBits.value);
2023
2024 // Update last coordinates of pointers that have moved so that we observe the new
2025 // pointer positions at the same time as other pointers that have just gone up.
2026 bool moveNeeded =
2027 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2028 mCurrentCookedState.cookedPointerData.pointerCoords,
2029 mCurrentCookedState.cookedPointerData.idToIndex,
2030 mLastCookedState.cookedPointerData.pointerProperties,
2031 mLastCookedState.cookedPointerData.pointerCoords,
2032 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2033 if (buttonState != mLastCookedState.buttonState) {
2034 moveNeeded = true;
2035 }
2036
2037 // Dispatch pointer up events.
2038 while (!upIdBits.isEmpty()) {
2039 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002040 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002041 if (isCanceled) {
2042 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2043 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002044 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2045 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2046 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2047 buttonState, 0,
2048 mLastCookedState.cookedPointerData.pointerProperties,
2049 mLastCookedState.cookedPointerData.pointerCoords,
2050 mLastCookedState.cookedPointerData.idToIndex,
2051 dispatchedIdBits, upId, mOrientedXPrecision,
2052 mOrientedYPrecision, mDownTime,
2053 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002054 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002055 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002056 }
2057
2058 // Dispatch move events if any of the remaining pointers moved from their old locations.
2059 // Although applications receive new locations as part of individual pointer up
2060 // events, they do not generally handle them except when presented in a move event.
2061 if (moveNeeded && !moveIdBits.isEmpty()) {
2062 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002063 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2064 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2065 mCurrentCookedState.cookedPointerData.pointerProperties,
2066 mCurrentCookedState.cookedPointerData.pointerCoords,
2067 mCurrentCookedState.cookedPointerData.idToIndex,
2068 dispatchedIdBits, -1, mOrientedXPrecision,
2069 mOrientedYPrecision, mDownTime,
2070 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002071 }
2072
2073 // Dispatch pointer down events using the new pointer locations.
2074 while (!downIdBits.isEmpty()) {
2075 uint32_t downId = downIdBits.clearFirstMarkedBit();
2076 dispatchedIdBits.markBit(downId);
2077
2078 if (dispatchedIdBits.count() == 1) {
2079 // First pointer is going down. Set down time.
2080 mDownTime = when;
2081 }
2082
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002083 out.push_back(
2084 dispatchMotion(when, readTime, policyFlags, mSource,
2085 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2086 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2087 mCurrentCookedState.cookedPointerData.pointerCoords,
2088 mCurrentCookedState.cookedPointerData.idToIndex,
2089 dispatchedIdBits, downId, mOrientedXPrecision,
2090 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002091 }
2092 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002093 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002094}
2095
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002096std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2097 uint32_t policyFlags) {
2098 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002099 if (mSentHoverEnter &&
2100 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2101 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2102 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002103 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2104 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2105 mLastCookedState.buttonState, 0,
2106 mLastCookedState.cookedPointerData.pointerProperties,
2107 mLastCookedState.cookedPointerData.pointerCoords,
2108 mLastCookedState.cookedPointerData.idToIndex,
2109 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2110 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2111 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002112 mSentHoverEnter = false;
2113 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002114 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002115}
2116
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002117std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2118 uint32_t policyFlags) {
2119 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002120 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2121 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2122 int32_t metaState = getContext()->getGlobalMetaState();
2123 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002124 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2125 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2126 mCurrentRawState.buttonState, 0,
2127 mCurrentCookedState.cookedPointerData.pointerProperties,
2128 mCurrentCookedState.cookedPointerData.pointerCoords,
2129 mCurrentCookedState.cookedPointerData.idToIndex,
2130 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2131 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2132 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002133 mSentHoverEnter = true;
2134 }
2135
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002136 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2137 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2138 mCurrentRawState.buttonState, 0,
2139 mCurrentCookedState.cookedPointerData.pointerProperties,
2140 mCurrentCookedState.cookedPointerData.pointerCoords,
2141 mCurrentCookedState.cookedPointerData.idToIndex,
2142 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2143 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2144 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002145 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002146 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002147}
2148
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002149std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2150 uint32_t policyFlags) {
2151 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002152 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2153 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2154 const int32_t metaState = getContext()->getGlobalMetaState();
2155 int32_t buttonState = mLastCookedState.buttonState;
2156 while (!releasedButtons.isEmpty()) {
2157 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2158 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002159 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2160 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2161 metaState, buttonState, 0,
2162 mCurrentCookedState.cookedPointerData.pointerProperties,
2163 mCurrentCookedState.cookedPointerData.pointerCoords,
2164 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2165 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2166 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002167 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002168 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002169}
2170
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002171std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2172 uint32_t policyFlags) {
2173 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002174 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2175 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2176 const int32_t metaState = getContext()->getGlobalMetaState();
2177 int32_t buttonState = mLastCookedState.buttonState;
2178 while (!pressedButtons.isEmpty()) {
2179 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2180 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002181 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2182 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2183 buttonState, 0,
2184 mCurrentCookedState.cookedPointerData.pointerProperties,
2185 mCurrentCookedState.cookedPointerData.pointerCoords,
2186 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2187 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2188 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002189 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002190 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002191}
2192
2193const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2194 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2195 return cookedPointerData.touchingIdBits;
2196 }
2197 return cookedPointerData.hoveringIdBits;
2198}
2199
2200void TouchInputMapper::cookPointerData() {
2201 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2202
2203 mCurrentCookedState.cookedPointerData.clear();
2204 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2205 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2206 mCurrentRawState.rawPointerData.hoveringIdBits;
2207 mCurrentCookedState.cookedPointerData.touchingIdBits =
2208 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002209 mCurrentCookedState.cookedPointerData.canceledIdBits =
2210 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002211
2212 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2213 mCurrentCookedState.buttonState = 0;
2214 } else {
2215 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2216 }
2217
2218 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002219 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002220 for (uint32_t i = 0; i < currentPointerCount; i++) {
2221 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2222
2223 // Size
2224 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2225 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002226 case Calibration::SizeCalibration::GEOMETRIC:
2227 case Calibration::SizeCalibration::DIAMETER:
2228 case Calibration::SizeCalibration::BOX:
2229 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002230 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2231 touchMajor = in.touchMajor;
2232 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2233 toolMajor = in.toolMajor;
2234 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2235 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2236 : in.touchMajor;
2237 } else if (mRawPointerAxes.touchMajor.valid) {
2238 toolMajor = touchMajor = in.touchMajor;
2239 toolMinor = touchMinor =
2240 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2241 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2242 : in.touchMajor;
2243 } else if (mRawPointerAxes.toolMajor.valid) {
2244 touchMajor = toolMajor = in.toolMajor;
2245 touchMinor = toolMinor =
2246 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2247 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2248 : in.toolMajor;
2249 } else {
2250 ALOG_ASSERT(false,
2251 "No touch or tool axes. "
2252 "Size calibration should have been resolved to NONE.");
2253 touchMajor = 0;
2254 touchMinor = 0;
2255 toolMajor = 0;
2256 toolMinor = 0;
2257 size = 0;
2258 }
2259
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002260 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002261 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2262 if (touchingCount > 1) {
2263 touchMajor /= touchingCount;
2264 touchMinor /= touchingCount;
2265 toolMajor /= touchingCount;
2266 toolMinor /= touchingCount;
2267 size /= touchingCount;
2268 }
2269 }
2270
Michael Wright227c5542020-07-02 18:30:52 +01002271 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002272 touchMajor *= mGeometricScale;
2273 touchMinor *= mGeometricScale;
2274 toolMajor *= mGeometricScale;
2275 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002276 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002277 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2278 touchMinor = touchMajor;
2279 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2280 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002281 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002282 touchMinor = touchMajor;
2283 toolMinor = toolMajor;
2284 }
2285
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002286 mCalibration.applySizeScaleAndBias(touchMajor);
2287 mCalibration.applySizeScaleAndBias(touchMinor);
2288 mCalibration.applySizeScaleAndBias(toolMajor);
2289 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002290 size *= mSizeScale;
2291 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002292 case Calibration::SizeCalibration::DEFAULT:
2293 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2294 break;
2295 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 touchMajor = 0;
2297 touchMinor = 0;
2298 toolMajor = 0;
2299 toolMinor = 0;
2300 size = 0;
2301 break;
2302 }
2303
2304 // Pressure
2305 float pressure;
2306 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002307 case Calibration::PressureCalibration::PHYSICAL:
2308 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002309 pressure = in.pressure * mPressureScale;
2310 break;
2311 default:
2312 pressure = in.isHovering ? 0 : 1;
2313 break;
2314 }
2315
2316 // Tilt and Orientation
2317 float tilt;
2318 float orientation;
2319 if (mHaveTilt) {
2320 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2321 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2322 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2323 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2324 } else {
2325 tilt = 0;
2326
2327 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002328 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002329 orientation = in.orientation * mOrientationScale;
2330 break;
Michael Wright227c5542020-07-02 18:30:52 +01002331 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2333 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2334 if (c1 != 0 || c2 != 0) {
2335 orientation = atan2f(c1, c2) * 0.5f;
2336 float confidence = hypotf(c1, c2);
2337 float scale = 1.0f + confidence / 16.0f;
2338 touchMajor *= scale;
2339 touchMinor /= scale;
2340 toolMajor *= scale;
2341 toolMinor /= scale;
2342 } else {
2343 orientation = 0;
2344 }
2345 break;
2346 }
2347 default:
2348 orientation = 0;
2349 }
2350 }
2351
2352 // Distance
2353 float distance;
2354 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002355 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 distance = in.distance * mDistanceScale;
2357 break;
2358 default:
2359 distance = 0;
2360 }
2361
2362 // Coverage
2363 int32_t rawLeft, rawTop, rawRight, rawBottom;
2364 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002365 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2367 rawRight = in.toolMinor & 0x0000ffff;
2368 rawBottom = in.toolMajor & 0x0000ffff;
2369 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2370 break;
2371 default:
2372 rawLeft = rawTop = rawRight = rawBottom = 0;
2373 break;
2374 }
2375
2376 // Adjust X,Y coords for device calibration
2377 // TODO: Adjust coverage coords?
2378 float xTransformed = in.x, yTransformed = in.y;
2379 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002380 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381
Prabir Pradhan1728b212021-10-19 16:00:03 -07002382 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 float left, top, right, bottom;
2384
Prabir Pradhan1728b212021-10-19 16:00:03 -07002385 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002386 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002387 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2388 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2389 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2390 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002392 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002394 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002395 }
2396 break;
2397 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2399 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002400 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2401 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002403 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002405 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 }
2407 break;
2408 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2410 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002411 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2412 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002413 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002414 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002416 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 }
2418 break;
2419 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002420 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2421 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2422 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2423 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002424 break;
2425 }
2426
2427 // Write output coords.
2428 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2429 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002430 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2431 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2433 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2434 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2435 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2436 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2437 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2438 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002439 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2441 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2442 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2443 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2444 } else {
2445 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2446 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2447 }
2448
Chris Ye364fdb52020-08-05 15:07:56 -07002449 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002450 uint32_t id = in.id;
2451 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2452 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2453 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2454 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2455 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2456 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2457 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2458 }
2459
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 // Write output properties.
2461 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462 properties.clear();
2463 properties.id = id;
2464 properties.toolType = in.toolType;
2465
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002466 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002468 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 }
2470}
2471
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002472std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2473 uint32_t policyFlags,
2474 PointerUsage pointerUsage) {
2475 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002477 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 mPointerUsage = pointerUsage;
2479 }
2480
2481 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002482 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002483 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002484 break;
Michael Wright227c5542020-07-02 18:30:52 +01002485 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002486 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002487 break;
Michael Wright227c5542020-07-02 18:30:52 +01002488 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002489 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 break;
Michael Wright227c5542020-07-02 18:30:52 +01002491 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002492 break;
2493 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002494 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002495}
2496
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002497std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2498 uint32_t policyFlags) {
2499 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002500 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002501 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002502 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 break;
Michael Wright227c5542020-07-02 18:30:52 +01002504 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002505 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002506 break;
Michael Wright227c5542020-07-02 18:30:52 +01002507 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002508 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 break;
Michael Wright227c5542020-07-02 18:30:52 +01002510 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 break;
2512 }
2513
Michael Wright227c5542020-07-02 18:30:52 +01002514 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002515 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516}
2517
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002518std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2519 uint32_t policyFlags,
2520 bool isTimeout) {
2521 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 // Update current gesture coordinates.
2523 bool cancelPreviousGesture, finishPreviousGesture;
2524 bool sendEvents =
2525 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2526 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002527 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 }
2529 if (finishPreviousGesture) {
2530 cancelPreviousGesture = false;
2531 }
2532
2533 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002534 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002535 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002536 if (finishPreviousGesture || cancelPreviousGesture) {
2537 mPointerController->clearSpots();
2538 }
2539
Michael Wright227c5542020-07-02 18:30:52 +01002540 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002541 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2542 mPointerGesture.currentGestureIdToIndex,
2543 mPointerGesture.currentGestureIdBits,
2544 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002545 }
2546 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002547 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002548 }
2549
2550 // Show or hide the pointer if needed.
2551 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002552 case PointerGesture::Mode::NEUTRAL:
2553 case PointerGesture::Mode::QUIET:
2554 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2555 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002556 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002557 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002558 }
2559 break;
Michael Wright227c5542020-07-02 18:30:52 +01002560 case PointerGesture::Mode::TAP:
2561 case PointerGesture::Mode::TAP_DRAG:
2562 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2563 case PointerGesture::Mode::HOVER:
2564 case PointerGesture::Mode::PRESS:
2565 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002566 // Unfade the pointer when the current gesture manipulates the
2567 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002568 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002569 break;
Michael Wright227c5542020-07-02 18:30:52 +01002570 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002571 // Fade the pointer when the current gesture manipulates a different
2572 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002573 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002574 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002575 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002576 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002577 }
2578 break;
2579 }
2580
2581 // Send events!
2582 int32_t metaState = getContext()->getGlobalMetaState();
2583 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002584 const MotionClassification classification =
2585 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2586 ? MotionClassification::TWO_FINGER_SWIPE
2587 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002588
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002589 uint32_t flags = 0;
2590
2591 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2592 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2593 }
2594
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002595 // Update last coordinates of pointers that have moved so that we observe the new
2596 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002597 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2598 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2599 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2600 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2601 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2602 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002603 bool moveNeeded = false;
2604 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2605 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2606 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2607 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2608 mPointerGesture.lastGestureIdBits.value);
2609 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2610 mPointerGesture.currentGestureCoords,
2611 mPointerGesture.currentGestureIdToIndex,
2612 mPointerGesture.lastGestureProperties,
2613 mPointerGesture.lastGestureCoords,
2614 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2615 if (buttonState != mLastCookedState.buttonState) {
2616 moveNeeded = true;
2617 }
2618 }
2619
2620 // Send motion events for all pointers that went up or were canceled.
2621 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2622 if (!dispatchedGestureIdBits.isEmpty()) {
2623 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002624 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002625 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002626 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002627 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2628 mPointerGesture.lastGestureProperties,
2629 mPointerGesture.lastGestureCoords,
2630 mPointerGesture.lastGestureIdToIndex,
2631 dispatchedGestureIdBits, -1, 0, 0,
2632 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002633
2634 dispatchedGestureIdBits.clear();
2635 } else {
2636 BitSet32 upGestureIdBits;
2637 if (finishPreviousGesture) {
2638 upGestureIdBits = dispatchedGestureIdBits;
2639 } else {
2640 upGestureIdBits.value =
2641 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2642 }
2643 while (!upGestureIdBits.isEmpty()) {
2644 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2645
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002646 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2647 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2648 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2649 mPointerGesture.lastGestureProperties,
2650 mPointerGesture.lastGestureCoords,
2651 mPointerGesture.lastGestureIdToIndex,
2652 dispatchedGestureIdBits, id, 0, 0,
2653 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002654
2655 dispatchedGestureIdBits.clearBit(id);
2656 }
2657 }
2658 }
2659
2660 // Send motion events for all pointers that moved.
2661 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002662 out.push_back(
2663 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2664 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2665 mPointerGesture.currentGestureProperties,
2666 mPointerGesture.currentGestureCoords,
2667 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2668 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002669 }
2670
2671 // Send motion events for all pointers that went down.
2672 if (down) {
2673 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2674 ~dispatchedGestureIdBits.value);
2675 while (!downGestureIdBits.isEmpty()) {
2676 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2677 dispatchedGestureIdBits.markBit(id);
2678
2679 if (dispatchedGestureIdBits.count() == 1) {
2680 mPointerGesture.downTime = when;
2681 }
2682
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002683 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2684 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2685 buttonState, 0, mPointerGesture.currentGestureProperties,
2686 mPointerGesture.currentGestureCoords,
2687 mPointerGesture.currentGestureIdToIndex,
2688 dispatchedGestureIdBits, id, 0, 0,
2689 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002690 }
2691 }
2692
2693 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002694 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002695 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2696 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2697 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2698 mPointerGesture.currentGestureProperties,
2699 mPointerGesture.currentGestureCoords,
2700 mPointerGesture.currentGestureIdToIndex,
2701 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2702 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002703 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2704 // Synthesize a hover move event after all pointers go up to indicate that
2705 // the pointer is hovering again even if the user is not currently touching
2706 // the touch pad. This ensures that a view will receive a fresh hover enter
2707 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002708 float x, y;
2709 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002710
2711 PointerProperties pointerProperties;
2712 pointerProperties.clear();
2713 pointerProperties.id = 0;
2714 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2715
2716 PointerCoords pointerCoords;
2717 pointerCoords.clear();
2718 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2719 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2720
2721 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002722 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2723 mSource, displayId, policyFlags,
2724 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2725 buttonState, MotionClassification::NONE,
2726 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2727 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2728 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002729 }
2730
2731 // Update state.
2732 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2733 if (!down) {
2734 mPointerGesture.lastGestureIdBits.clear();
2735 } else {
2736 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2737 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2738 uint32_t id = idBits.clearFirstMarkedBit();
2739 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2740 mPointerGesture.lastGestureProperties[index].copyFrom(
2741 mPointerGesture.currentGestureProperties[index]);
2742 mPointerGesture.lastGestureCoords[index].copyFrom(
2743 mPointerGesture.currentGestureCoords[index]);
2744 mPointerGesture.lastGestureIdToIndex[id] = index;
2745 }
2746 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002747 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002748}
2749
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002750std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2751 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002752 const MotionClassification classification =
2753 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2754 ? MotionClassification::TWO_FINGER_SWIPE
2755 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002756 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002757 // Cancel previously dispatches pointers.
2758 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2759 int32_t metaState = getContext()->getGlobalMetaState();
2760 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002761 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002762 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2763 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002764 mPointerGesture.lastGestureProperties,
2765 mPointerGesture.lastGestureCoords,
2766 mPointerGesture.lastGestureIdToIndex,
2767 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2768 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002769 }
2770
2771 // Reset the current pointer gesture.
2772 mPointerGesture.reset();
2773 mPointerVelocityControl.reset();
2774
2775 // Remove any current spots.
2776 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002777 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002778 mPointerController->clearSpots();
2779 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002780 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002781}
2782
2783bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2784 bool* outFinishPreviousGesture, bool isTimeout) {
2785 *outCancelPreviousGesture = false;
2786 *outFinishPreviousGesture = false;
2787
2788 // Handle TAP timeout.
2789 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002790 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002791
Michael Wright227c5542020-07-02 18:30:52 +01002792 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002793 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2794 // The tap/drag timeout has not yet expired.
2795 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2796 mConfig.pointerGestureTapDragInterval);
2797 } else {
2798 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002799 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002800 *outFinishPreviousGesture = true;
2801
2802 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002803 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002804 mPointerGesture.currentGestureIdBits.clear();
2805
2806 mPointerVelocityControl.reset();
2807 return true;
2808 }
2809 }
2810
2811 // We did not handle this timeout.
2812 return false;
2813 }
2814
2815 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2816 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2817
2818 // Update the velocity tracker.
2819 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002820 std::vector<float> positionsX;
2821 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002822 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823 uint32_t id = idBits.clearFirstMarkedBit();
2824 const RawPointerData::Pointer& pointer =
2825 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002826 positionsX.push_back(pointer.x * mPointerXMovementScale);
2827 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002828 }
2829 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002830 {{AMOTION_EVENT_AXIS_X, positionsX},
2831 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002832 }
2833
2834 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2835 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002836 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2837 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2838 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002839 mPointerGesture.resetTap();
2840 }
2841
2842 // Pick a new active touch id if needed.
2843 // Choose an arbitrary pointer that just went down, if there is one.
2844 // Otherwise choose an arbitrary remaining pointer.
2845 // This guarantees we always have an active touch id when there is at least one pointer.
2846 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002847 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002848 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002849 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002850 mPointerGesture.firstTouchTime = when;
2851 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002852 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2853 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2854 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2855 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002857 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002858
2859 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002860 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002861 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002862 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2863 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2864 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002865 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002866 *outFinishPreviousGesture = true;
2867 }
2868
2869 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002870 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002871 mPointerGesture.currentGestureIdBits.clear();
2872
2873 mPointerVelocityControl.reset();
2874 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2875 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2876 // The pointer follows the active touch point.
2877 // Emit DOWN, MOVE, UP events at the pointer location.
2878 //
2879 // Only the active touch matters; other fingers are ignored. This policy helps
2880 // to handle the case where the user places a second finger on the touch pad
2881 // to apply the necessary force to depress an integrated button below the surface.
2882 // We don't want the second finger to be delivered to applications.
2883 //
2884 // For this to work well, we need to make sure to track the pointer that is really
2885 // active. If the user first puts one finger down to click then adds another
2886 // finger to drag then the active pointer should switch to the finger that is
2887 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002888 ALOGD_IF(DEBUG_GESTURES,
2889 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2890 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002892 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002893 *outFinishPreviousGesture = true;
2894 mPointerGesture.activeGestureId = 0;
2895 }
2896
2897 // Switch pointers if needed.
2898 // Find the fastest pointer and follow it.
2899 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002900 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002901 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002902 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002903 ALOGD_IF(DEBUG_GESTURES,
2904 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2905 "bestSpeed=%0.3f",
2906 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 }
2908 }
2909
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002911 // When using spots, the click will occur at the position of the anchor
2912 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002913 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002914 } else {
2915 mPointerVelocityControl.reset();
2916 }
2917
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002918 float x, y;
2919 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920
Michael Wright227c5542020-07-02 18:30:52 +01002921 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 mPointerGesture.currentGestureIdBits.clear();
2923 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2924 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2925 mPointerGesture.currentGestureProperties[0].clear();
2926 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2927 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2928 mPointerGesture.currentGestureCoords[0].clear();
2929 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2930 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2931 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2932 } else if (currentFingerCount == 0) {
2933 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002934 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002935 *outFinishPreviousGesture = true;
2936 }
2937
2938 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2939 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2940 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002941 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2942 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943 lastFingerCount == 1) {
2944 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002945 float x, y;
2946 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002947 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2948 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002949 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950
2951 mPointerGesture.tapUpTime = when;
2952 getContext()->requestTimeoutAtTime(when +
2953 mConfig.pointerGestureTapDragInterval);
2954
2955 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002956 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002957 mPointerGesture.currentGestureIdBits.clear();
2958 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2959 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2960 mPointerGesture.currentGestureProperties[0].clear();
2961 mPointerGesture.currentGestureProperties[0].id =
2962 mPointerGesture.activeGestureId;
2963 mPointerGesture.currentGestureProperties[0].toolType =
2964 AMOTION_EVENT_TOOL_TYPE_FINGER;
2965 mPointerGesture.currentGestureCoords[0].clear();
2966 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2967 mPointerGesture.tapX);
2968 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2969 mPointerGesture.tapY);
2970 mPointerGesture.currentGestureCoords[0]
2971 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2972
2973 tapped = true;
2974 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002975 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2976 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002977 }
2978 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002979 if (DEBUG_GESTURES) {
2980 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2981 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2982 (when - mPointerGesture.tapDownTime) * 0.000001f);
2983 } else {
2984 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2985 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002987 }
2988 }
2989
2990 mPointerVelocityControl.reset();
2991
2992 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002993 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002994 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002995 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 mPointerGesture.currentGestureIdBits.clear();
2997 }
2998 } else if (currentFingerCount == 1) {
2999 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3000 // The pointer follows the active touch point.
3001 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3002 // When in TAP_DRAG, emit MOVE events at the pointer location.
3003 ALOG_ASSERT(activeTouchId >= 0);
3004
Michael Wright227c5542020-07-02 18:30:52 +01003005 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3006 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003007 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003008 float x, y;
3009 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003010 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3011 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003012 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003013 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003014 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3015 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003016 }
3017 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003018 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3019 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003020 }
Michael Wright227c5542020-07-02 18:30:52 +01003021 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3022 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003023 }
3024
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003025 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003026 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003027 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003028 } else {
3029 mPointerVelocityControl.reset();
3030 }
3031
3032 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003033 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003034 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003035 down = true;
3036 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003037 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003038 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003039 *outFinishPreviousGesture = true;
3040 }
3041 mPointerGesture.activeGestureId = 0;
3042 down = false;
3043 }
3044
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003045 float x, y;
3046 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047
3048 mPointerGesture.currentGestureIdBits.clear();
3049 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3050 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3051 mPointerGesture.currentGestureProperties[0].clear();
3052 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3053 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3054 mPointerGesture.currentGestureCoords[0].clear();
3055 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3056 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3057 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3058 down ? 1.0f : 0.0f);
3059
3060 if (lastFingerCount == 0 && currentFingerCount != 0) {
3061 mPointerGesture.resetTap();
3062 mPointerGesture.tapDownTime = when;
3063 mPointerGesture.tapX = x;
3064 mPointerGesture.tapY = y;
3065 }
3066 } else {
3067 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003068 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003069 }
3070
3071 mPointerController->setButtonState(mCurrentRawState.buttonState);
3072
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003073 if (DEBUG_GESTURES) {
3074 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3075 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3076 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3077 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3078 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3079 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3080 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3081 uint32_t id = idBits.clearFirstMarkedBit();
3082 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3083 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3084 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3085 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3086 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3087 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3088 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3089 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3090 }
3091 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3092 uint32_t id = idBits.clearFirstMarkedBit();
3093 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3094 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3095 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3096 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3097 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3098 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3099 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3100 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3101 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003102 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003103 return true;
3104}
3105
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003106bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3107 if (mPointerGesture.activeTouchId < 0) {
3108 mPointerGesture.resetQuietTime();
3109 return false;
3110 }
3111
3112 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3113 return true;
3114 }
3115
3116 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3117 bool isQuietTime = false;
3118 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3119 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3120 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3121 currentFingerCount < 2) {
3122 // Enter quiet time when exiting swipe or freeform state.
3123 // This is to prevent accidentally entering the hover state and flinging the
3124 // pointer when finishing a swipe and there is still one pointer left onscreen.
3125 isQuietTime = true;
3126 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3127 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3128 // Enter quiet time when releasing the button and there are still two or more
3129 // fingers down. This may indicate that one finger was used to press the button
3130 // but it has not gone up yet.
3131 isQuietTime = true;
3132 }
3133 if (isQuietTime) {
3134 mPointerGesture.quietTime = when;
3135 }
3136 return isQuietTime;
3137}
3138
3139std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3140 int32_t bestId = -1;
3141 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3142 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3143 uint32_t id = idBits.clearFirstMarkedBit();
3144 std::optional<float> vx =
3145 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3146 std::optional<float> vy =
3147 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3148 if (vx && vy) {
3149 float speed = hypotf(*vx, *vy);
3150 if (speed > bestSpeed) {
3151 bestId = id;
3152 bestSpeed = speed;
3153 }
3154 }
3155 }
3156 return std::make_pair(bestId, bestSpeed);
3157}
3158
3159void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3160 bool* finishPreviousGesture) {
3161 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3162 // to move before deciding what to do.
3163 //
3164 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3165 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3166 // just a press or long-press at the pointer location.
3167 //
3168 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3169 // pointer location.
3170 //
3171 // When the two fingers move enough or when additional fingers are added, we make a decision to
3172 // transition into SWIPE or FREEFORM mode accordingly.
3173 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3174 ALOG_ASSERT(activeTouchId >= 0);
3175
3176 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3177 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3178 bool settled =
3179 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3180 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3181 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3182 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3183 *finishPreviousGesture = true;
3184 } else if (!settled && currentFingerCount > lastFingerCount) {
3185 // Additional pointers have gone down but not yet settled.
3186 // Reset the gesture.
3187 ALOGD_IF(DEBUG_GESTURES,
3188 "Gestures: Resetting gesture since additional pointers went down for "
3189 "MULTITOUCH, settle time remaining %0.3fms",
3190 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3191 when) * 0.000001f);
3192 *cancelPreviousGesture = true;
3193 } else {
3194 // Continue previous gesture.
3195 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3196 }
3197
3198 if (*finishPreviousGesture || *cancelPreviousGesture) {
3199 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3200 mPointerGesture.activeGestureId = 0;
3201 mPointerGesture.referenceIdBits.clear();
3202 mPointerVelocityControl.reset();
3203
3204 // Use the centroid and pointer location as the reference points for the gesture.
3205 ALOGD_IF(DEBUG_GESTURES,
3206 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3207 "%0.3fms",
3208 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3209 when) * 0.000001f);
3210 mCurrentRawState.rawPointerData
3211 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3212 &mPointerGesture.referenceTouchY);
3213 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3214 &mPointerGesture.referenceGestureY);
3215 }
3216
3217 // Clear the reference deltas for fingers not yet included in the reference calculation.
3218 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3219 ~mPointerGesture.referenceIdBits.value);
3220 !idBits.isEmpty();) {
3221 uint32_t id = idBits.clearFirstMarkedBit();
3222 mPointerGesture.referenceDeltas[id].dx = 0;
3223 mPointerGesture.referenceDeltas[id].dy = 0;
3224 }
3225 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3226
3227 // Add delta for all fingers and calculate a common movement delta.
3228 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3229 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3230 mCurrentCookedState.fingerIdBits.value);
3231 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3232 bool first = (idBits == commonIdBits);
3233 uint32_t id = idBits.clearFirstMarkedBit();
3234 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3235 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3236 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3237 delta.dx += cpd.x - lpd.x;
3238 delta.dy += cpd.y - lpd.y;
3239
3240 if (first) {
3241 commonDeltaRawX = delta.dx;
3242 commonDeltaRawY = delta.dy;
3243 } else {
3244 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3245 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3246 }
3247 }
3248
3249 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3250 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3251 float dist[MAX_POINTER_ID + 1];
3252 int32_t distOverThreshold = 0;
3253 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3254 uint32_t id = idBits.clearFirstMarkedBit();
3255 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3256 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3257 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3258 distOverThreshold += 1;
3259 }
3260 }
3261
3262 // Only transition when at least two pointers have moved further than
3263 // the minimum distance threshold.
3264 if (distOverThreshold >= 2) {
3265 if (currentFingerCount > 2) {
3266 // There are more than two pointers, switch to FREEFORM.
3267 ALOGD_IF(DEBUG_GESTURES,
3268 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3269 currentFingerCount);
3270 *cancelPreviousGesture = true;
3271 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3272 } else {
3273 // There are exactly two pointers.
3274 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3275 uint32_t id1 = idBits.clearFirstMarkedBit();
3276 uint32_t id2 = idBits.firstMarkedBit();
3277 const RawPointerData::Pointer& p1 =
3278 mCurrentRawState.rawPointerData.pointerForId(id1);
3279 const RawPointerData::Pointer& p2 =
3280 mCurrentRawState.rawPointerData.pointerForId(id2);
3281 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3282 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3283 // There are two pointers but they are too far apart for a SWIPE,
3284 // switch to FREEFORM.
3285 ALOGD_IF(DEBUG_GESTURES,
3286 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3287 mutualDistance, mPointerGestureMaxSwipeWidth);
3288 *cancelPreviousGesture = true;
3289 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3290 } else {
3291 // There are two pointers. Wait for both pointers to start moving
3292 // before deciding whether this is a SWIPE or FREEFORM gesture.
3293 float dist1 = dist[id1];
3294 float dist2 = dist[id2];
3295 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3296 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3297 // Calculate the dot product of the displacement vectors.
3298 // When the vectors are oriented in approximately the same direction,
3299 // the angle betweeen them is near zero and the cosine of the angle
3300 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3301 // mag(v2).
3302 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3303 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3304 float dx1 = delta1.dx * mPointerXZoomScale;
3305 float dy1 = delta1.dy * mPointerYZoomScale;
3306 float dx2 = delta2.dx * mPointerXZoomScale;
3307 float dy2 = delta2.dy * mPointerYZoomScale;
3308 float dot = dx1 * dx2 + dy1 * dy2;
3309 float cosine = dot / (dist1 * dist2); // denominator always > 0
3310 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3311 // Pointers are moving in the same direction. Switch to SWIPE.
3312 ALOGD_IF(DEBUG_GESTURES,
3313 "Gestures: PRESS transitioned to SWIPE, "
3314 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3315 "cosine %0.3f >= %0.3f",
3316 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3317 mConfig.pointerGestureMultitouchMinDistance, cosine,
3318 mConfig.pointerGestureSwipeTransitionAngleCosine);
3319 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3320 } else {
3321 // Pointers are moving in different directions. Switch to FREEFORM.
3322 ALOGD_IF(DEBUG_GESTURES,
3323 "Gestures: PRESS transitioned to FREEFORM, "
3324 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3325 "cosine %0.3f < %0.3f",
3326 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3327 mConfig.pointerGestureMultitouchMinDistance, cosine,
3328 mConfig.pointerGestureSwipeTransitionAngleCosine);
3329 *cancelPreviousGesture = true;
3330 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3331 }
3332 }
3333 }
3334 }
3335 }
3336 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3337 // Switch from SWIPE to FREEFORM if additional pointers go down.
3338 // Cancel previous gesture.
3339 if (currentFingerCount > 2) {
3340 ALOGD_IF(DEBUG_GESTURES,
3341 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3342 currentFingerCount);
3343 *cancelPreviousGesture = true;
3344 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3345 }
3346 }
3347
3348 // Move the reference points based on the overall group motion of the fingers
3349 // except in PRESS mode while waiting for a transition to occur.
3350 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3351 (commonDeltaRawX || commonDeltaRawY)) {
3352 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3353 uint32_t id = idBits.clearFirstMarkedBit();
3354 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3355 delta.dx = 0;
3356 delta.dy = 0;
3357 }
3358
3359 mPointerGesture.referenceTouchX += commonDeltaRawX;
3360 mPointerGesture.referenceTouchY += commonDeltaRawY;
3361
3362 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3363 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3364
3365 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3366 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3367
3368 mPointerGesture.referenceGestureX += commonDeltaX;
3369 mPointerGesture.referenceGestureY += commonDeltaY;
3370 }
3371
3372 // Report gestures.
3373 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3374 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3375 // PRESS or SWIPE mode.
3376 ALOGD_IF(DEBUG_GESTURES,
3377 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3378 "currentTouchPointerCount=%d",
3379 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3380 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3381
3382 mPointerGesture.currentGestureIdBits.clear();
3383 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3384 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3385 mPointerGesture.currentGestureProperties[0].clear();
3386 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3387 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3388 mPointerGesture.currentGestureCoords[0].clear();
3389 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3390 mPointerGesture.referenceGestureX);
3391 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3392 mPointerGesture.referenceGestureY);
3393 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3394 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3395 float xOffset = static_cast<float>(commonDeltaRawX) /
3396 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3397 float yOffset = static_cast<float>(commonDeltaRawY) /
3398 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3399 mPointerGesture.currentGestureCoords[0]
3400 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3401 mPointerGesture.currentGestureCoords[0]
3402 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3403 }
3404 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3405 // FREEFORM mode.
3406 ALOGD_IF(DEBUG_GESTURES,
3407 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3408 "currentTouchPointerCount=%d",
3409 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3410 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3411
3412 mPointerGesture.currentGestureIdBits.clear();
3413
3414 BitSet32 mappedTouchIdBits;
3415 BitSet32 usedGestureIdBits;
3416 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3417 // Initially, assign the active gesture id to the active touch point
3418 // if there is one. No other touch id bits are mapped yet.
3419 if (!*cancelPreviousGesture) {
3420 mappedTouchIdBits.markBit(activeTouchId);
3421 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3422 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3423 mPointerGesture.activeGestureId;
3424 } else {
3425 mPointerGesture.activeGestureId = -1;
3426 }
3427 } else {
3428 // Otherwise, assume we mapped all touches from the previous frame.
3429 // Reuse all mappings that are still applicable.
3430 mappedTouchIdBits.value =
3431 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3432 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3433
3434 // Check whether we need to choose a new active gesture id because the
3435 // current went went up.
3436 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3437 ~mCurrentCookedState.fingerIdBits.value);
3438 !upTouchIdBits.isEmpty();) {
3439 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3440 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3441 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3442 mPointerGesture.activeGestureId = -1;
3443 break;
3444 }
3445 }
3446 }
3447
3448 ALOGD_IF(DEBUG_GESTURES,
3449 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3450 "activeGestureId=%d",
3451 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3452
3453 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3454 for (uint32_t i = 0; i < currentFingerCount; i++) {
3455 uint32_t touchId = idBits.clearFirstMarkedBit();
3456 uint32_t gestureId;
3457 if (!mappedTouchIdBits.hasBit(touchId)) {
3458 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3459 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3460 ALOGD_IF(DEBUG_GESTURES,
3461 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3462 gestureId);
3463 } else {
3464 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3465 ALOGD_IF(DEBUG_GESTURES,
3466 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3467 touchId, gestureId);
3468 }
3469 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3470 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3471
3472 const RawPointerData::Pointer& pointer =
3473 mCurrentRawState.rawPointerData.pointerForId(touchId);
3474 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3475 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3476 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3477
3478 mPointerGesture.currentGestureProperties[i].clear();
3479 mPointerGesture.currentGestureProperties[i].id = gestureId;
3480 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3481 mPointerGesture.currentGestureCoords[i].clear();
3482 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3483 mPointerGesture.referenceGestureX +
3484 deltaX);
3485 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3486 mPointerGesture.referenceGestureY +
3487 deltaY);
3488 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3489 }
3490
3491 if (mPointerGesture.activeGestureId < 0) {
3492 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3493 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3494 mPointerGesture.activeGestureId);
3495 }
3496 }
3497}
3498
Harry Cutts714d1ad2022-08-24 16:36:43 +00003499void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3500 const RawPointerData::Pointer& currentPointer =
3501 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3502 const RawPointerData::Pointer& lastPointer =
3503 mLastRawState.rawPointerData.pointerForId(pointerId);
3504 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3505 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3506
3507 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3508 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3509
3510 mPointerController->move(deltaX, deltaY);
3511}
3512
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003513std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3514 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515 mPointerSimple.currentCoords.clear();
3516 mPointerSimple.currentProperties.clear();
3517
3518 bool down, hovering;
3519 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3520 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3521 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003522 mPointerController
3523 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3524 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003525
3526 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3527 down = !hovering;
3528
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003529 float x, y;
3530 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003531 mPointerSimple.currentCoords.copyFrom(
3532 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3533 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3534 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3535 mPointerSimple.currentProperties.id = 0;
3536 mPointerSimple.currentProperties.toolType =
3537 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3538 } else {
3539 down = false;
3540 hovering = false;
3541 }
3542
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003543 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003544}
3545
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003546std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3547 uint32_t policyFlags) {
3548 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003549}
3550
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003551std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3552 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003553 mPointerSimple.currentCoords.clear();
3554 mPointerSimple.currentProperties.clear();
3555
3556 bool down, hovering;
3557 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3558 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003559 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003560 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003561 } else {
3562 mPointerVelocityControl.reset();
3563 }
3564
3565 down = isPointerDown(mCurrentRawState.buttonState);
3566 hovering = !down;
3567
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003568 float x, y;
3569 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003570 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571 mPointerSimple.currentCoords.copyFrom(
3572 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3573 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3574 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3575 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3576 hovering ? 0.0f : 1.0f);
3577 mPointerSimple.currentProperties.id = 0;
3578 mPointerSimple.currentProperties.toolType =
3579 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3580 } else {
3581 mPointerVelocityControl.reset();
3582
3583 down = false;
3584 hovering = false;
3585 }
3586
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003587 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003588}
3589
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003590std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3591 uint32_t policyFlags) {
3592 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593
3594 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003595
3596 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003597}
3598
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003599std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3600 uint32_t policyFlags, bool down,
3601 bool hovering) {
3602 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003603 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003604
3605 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003606 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003607 mPointerController->clearSpots();
3608 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003609 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003610 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003611 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003612 }
Garfield Tan9514d782020-11-10 16:37:23 -08003613 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003614
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003615 float xCursorPosition, yCursorPosition;
3616 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003617
3618 if (mPointerSimple.down && !down) {
3619 mPointerSimple.down = false;
3620
3621 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003622 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3623 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3624 0, metaState, mLastRawState.buttonState,
3625 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3626 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3627 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3628 yCursorPosition, mPointerSimple.downTime,
3629 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003630 }
3631
3632 if (mPointerSimple.hovering && !hovering) {
3633 mPointerSimple.hovering = false;
3634
3635 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003636 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3637 mSource, displayId, policyFlags,
3638 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3639 mLastRawState.buttonState, MotionClassification::NONE,
3640 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3641 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3642 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3643 yCursorPosition, mPointerSimple.downTime,
3644 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003645 }
3646
3647 if (down) {
3648 if (!mPointerSimple.down) {
3649 mPointerSimple.down = true;
3650 mPointerSimple.downTime = when;
3651
3652 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003653 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3654 mSource, displayId, policyFlags,
3655 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3656 mCurrentRawState.buttonState, MotionClassification::NONE,
3657 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3658 &mPointerSimple.currentProperties,
3659 &mPointerSimple.currentCoords, mOrientedXPrecision,
3660 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3661 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003662 }
3663
3664 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003665 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3666 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3667 0, 0, metaState, mCurrentRawState.buttonState,
3668 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3669 &mPointerSimple.currentProperties,
3670 &mPointerSimple.currentCoords, mOrientedXPrecision,
3671 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3672 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003673 }
3674
3675 if (hovering) {
3676 if (!mPointerSimple.hovering) {
3677 mPointerSimple.hovering = true;
3678
3679 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003680 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3681 mSource, displayId, policyFlags,
3682 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3683 mCurrentRawState.buttonState, MotionClassification::NONE,
3684 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3685 &mPointerSimple.currentProperties,
3686 &mPointerSimple.currentCoords, mOrientedXPrecision,
3687 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3688 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003689 }
3690
3691 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003692 out.push_back(
3693 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3694 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3695 metaState, mCurrentRawState.buttonState,
3696 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3697 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3698 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3699 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003700 }
3701
3702 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3703 float vscroll = mCurrentRawState.rawVScroll;
3704 float hscroll = mCurrentRawState.rawHScroll;
3705 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3706 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3707
3708 // Send scroll.
3709 PointerCoords pointerCoords;
3710 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3711 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3712 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3713
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003714 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3715 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3716 0, 0, metaState, mCurrentRawState.buttonState,
3717 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3718 &mPointerSimple.currentProperties, &pointerCoords,
3719 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3720 yCursorPosition, mPointerSimple.downTime,
3721 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003722 }
3723
3724 // Save state.
3725 if (down || hovering) {
3726 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3727 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3728 } else {
3729 mPointerSimple.reset();
3730 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003731 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003732}
3733
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003734std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3735 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003736 mPointerSimple.currentCoords.clear();
3737 mPointerSimple.currentProperties.clear();
3738
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003739 return dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003740}
3741
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003742NotifyMotionArgs TouchInputMapper::dispatchMotion(
3743 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3744 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
3745 int32_t edgeFlags, const PointerProperties* properties, const PointerCoords* coords,
3746 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
3747 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003748 PointerCoords pointerCoords[MAX_POINTERS];
3749 PointerProperties pointerProperties[MAX_POINTERS];
3750 uint32_t pointerCount = 0;
3751 while (!idBits.isEmpty()) {
3752 uint32_t id = idBits.clearFirstMarkedBit();
3753 uint32_t index = idToIndex[id];
3754 pointerProperties[pointerCount].copyFrom(properties[index]);
3755 pointerCoords[pointerCount].copyFrom(coords[index]);
3756
3757 if (changedId >= 0 && id == uint32_t(changedId)) {
3758 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3759 }
3760
3761 pointerCount += 1;
3762 }
3763
3764 ALOG_ASSERT(pointerCount != 0);
3765
3766 if (changedId >= 0 && pointerCount == 1) {
3767 // Replace initial down and final up action.
3768 // We can compare the action without masking off the changed pointer index
3769 // because we know the index is 0.
3770 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3771 action = AMOTION_EVENT_ACTION_DOWN;
3772 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003773 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3774 action = AMOTION_EVENT_ACTION_CANCEL;
3775 } else {
3776 action = AMOTION_EVENT_ACTION_UP;
3777 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003778 } else {
3779 // Can't happen.
3780 ALOG_ASSERT(false);
3781 }
3782 }
3783 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3784 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003785 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003786 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003787 }
3788 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3789 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003790 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003791 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003792 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003793 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3794 policyFlags, action, actionButton, flags, metaState, buttonState,
3795 classification, edgeFlags, pointerCount, pointerProperties,
3796 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3797 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003798}
3799
3800bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3801 const PointerCoords* inCoords,
3802 const uint32_t* inIdToIndex,
3803 PointerProperties* outProperties,
3804 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3805 BitSet32 idBits) const {
3806 bool changed = false;
3807 while (!idBits.isEmpty()) {
3808 uint32_t id = idBits.clearFirstMarkedBit();
3809 uint32_t inIndex = inIdToIndex[id];
3810 uint32_t outIndex = outIdToIndex[id];
3811
3812 const PointerProperties& curInProperties = inProperties[inIndex];
3813 const PointerCoords& curInCoords = inCoords[inIndex];
3814 PointerProperties& curOutProperties = outProperties[outIndex];
3815 PointerCoords& curOutCoords = outCoords[outIndex];
3816
3817 if (curInProperties != curOutProperties) {
3818 curOutProperties.copyFrom(curInProperties);
3819 changed = true;
3820 }
3821
3822 if (curInCoords != curOutCoords) {
3823 curOutCoords.copyFrom(curInCoords);
3824 changed = true;
3825 }
3826 }
3827 return changed;
3828}
3829
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003830std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3831 std::list<NotifyArgs> out;
3832 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3833 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3834 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003835}
3836
Prabir Pradhan1728b212021-10-19 16:00:03 -07003837// Transform input device coordinates to display panel coordinates.
3838void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003839 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3840 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3841
arthurhunga36b28e2020-12-29 20:28:15 +08003842 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3843 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3844
Prabir Pradhan1728b212021-10-19 16:00:03 -07003845 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003846 // 0 - no swap and reverse.
3847 // 90 - swap x/y and reverse y.
3848 // 180 - reverse x, y.
3849 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003850 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003851 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003852 x = xScaled;
3853 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003854 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003855 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003856 y = xScaledMax;
3857 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003858 break;
3859 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003860 x = xScaledMax;
3861 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003862 break;
3863 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003864 y = xScaled;
3865 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003866 break;
3867 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003868 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003869 }
3870}
3871
Prabir Pradhan1728b212021-10-19 16:00:03 -07003872bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003873 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3874 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3875
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003876 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003877 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003878 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003879 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003880}
3881
3882const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3883 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003884 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3885 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3886 "left=%d, top=%d, right=%d, bottom=%d",
3887 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3888 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003889
3890 if (virtualKey.isHit(x, y)) {
3891 return &virtualKey;
3892 }
3893 }
3894
3895 return nullptr;
3896}
3897
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003898void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3899 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3900 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003901
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003902 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003903
3904 if (currentPointerCount == 0) {
3905 // No pointers to assign.
3906 return;
3907 }
3908
3909 if (lastPointerCount == 0) {
3910 // All pointers are new.
3911 for (uint32_t i = 0; i < currentPointerCount; i++) {
3912 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003913 current.rawPointerData.pointers[i].id = id;
3914 current.rawPointerData.idToIndex[id] = i;
3915 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003916 }
3917 return;
3918 }
3919
3920 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003921 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003922 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003923 uint32_t id = last.rawPointerData.pointers[0].id;
3924 current.rawPointerData.pointers[0].id = id;
3925 current.rawPointerData.idToIndex[id] = 0;
3926 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003927 return;
3928 }
3929
3930 // General case.
3931 // We build a heap of squared euclidean distances between current and last pointers
3932 // associated with the current and last pointer indices. Then, we find the best
3933 // match (by distance) for each current pointer.
3934 // The pointers must have the same tool type but it is possible for them to
3935 // transition from hovering to touching or vice-versa while retaining the same id.
3936 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3937
3938 uint32_t heapSize = 0;
3939 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3940 currentPointerIndex++) {
3941 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3942 lastPointerIndex++) {
3943 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003944 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003945 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003946 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003947 if (currentPointer.toolType == lastPointer.toolType) {
3948 int64_t deltaX = currentPointer.x - lastPointer.x;
3949 int64_t deltaY = currentPointer.y - lastPointer.y;
3950
3951 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3952
3953 // Insert new element into the heap (sift up).
3954 heap[heapSize].currentPointerIndex = currentPointerIndex;
3955 heap[heapSize].lastPointerIndex = lastPointerIndex;
3956 heap[heapSize].distance = distance;
3957 heapSize += 1;
3958 }
3959 }
3960 }
3961
3962 // Heapify
3963 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3964 startIndex -= 1;
3965 for (uint32_t parentIndex = startIndex;;) {
3966 uint32_t childIndex = parentIndex * 2 + 1;
3967 if (childIndex >= heapSize) {
3968 break;
3969 }
3970
3971 if (childIndex + 1 < heapSize &&
3972 heap[childIndex + 1].distance < heap[childIndex].distance) {
3973 childIndex += 1;
3974 }
3975
3976 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3977 break;
3978 }
3979
3980 swap(heap[parentIndex], heap[childIndex]);
3981 parentIndex = childIndex;
3982 }
3983 }
3984
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003985 if (DEBUG_POINTER_ASSIGNMENT) {
3986 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3987 for (size_t i = 0; i < heapSize; i++) {
3988 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3989 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3990 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003991 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003992
3993 // Pull matches out by increasing order of distance.
3994 // To avoid reassigning pointers that have already been matched, the loop keeps track
3995 // of which last and current pointers have been matched using the matchedXXXBits variables.
3996 // It also tracks the used pointer id bits.
3997 BitSet32 matchedLastBits(0);
3998 BitSet32 matchedCurrentBits(0);
3999 BitSet32 usedIdBits(0);
4000 bool first = true;
4001 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
4002 while (heapSize > 0) {
4003 if (first) {
4004 // The first time through the loop, we just consume the root element of
4005 // the heap (the one with smallest distance).
4006 first = false;
4007 } else {
4008 // Previous iterations consumed the root element of the heap.
4009 // Pop root element off of the heap (sift down).
4010 heap[0] = heap[heapSize];
4011 for (uint32_t parentIndex = 0;;) {
4012 uint32_t childIndex = parentIndex * 2 + 1;
4013 if (childIndex >= heapSize) {
4014 break;
4015 }
4016
4017 if (childIndex + 1 < heapSize &&
4018 heap[childIndex + 1].distance < heap[childIndex].distance) {
4019 childIndex += 1;
4020 }
4021
4022 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4023 break;
4024 }
4025
4026 swap(heap[parentIndex], heap[childIndex]);
4027 parentIndex = childIndex;
4028 }
4029
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004030 if (DEBUG_POINTER_ASSIGNMENT) {
4031 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4032 for (size_t j = 0; j < heapSize; j++) {
4033 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4034 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4035 heap[j].distance);
4036 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004037 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004038 }
4039
4040 heapSize -= 1;
4041
4042 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4043 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4044
4045 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4046 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4047
4048 matchedCurrentBits.markBit(currentPointerIndex);
4049 matchedLastBits.markBit(lastPointerIndex);
4050
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004051 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4052 current.rawPointerData.pointers[currentPointerIndex].id = id;
4053 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4054 current.rawPointerData.markIdBit(id,
4055 current.rawPointerData.isHovering(
4056 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004057 usedIdBits.markBit(id);
4058
Harry Cutts45483602022-08-24 14:36:48 +00004059 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4060 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4061 ", distance=%" PRIu64,
4062 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004063 break;
4064 }
4065 }
4066
4067 // Assign fresh ids to pointers that were not matched in the process.
4068 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4069 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4070 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4071
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004072 current.rawPointerData.pointers[currentPointerIndex].id = id;
4073 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4074 current.rawPointerData.markIdBit(id,
4075 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004076
Harry Cutts45483602022-08-24 14:36:48 +00004077 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4078 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4079 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004080 }
4081}
4082
4083int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4084 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4085 return AKEY_STATE_VIRTUAL;
4086 }
4087
4088 for (const VirtualKey& virtualKey : mVirtualKeys) {
4089 if (virtualKey.keyCode == keyCode) {
4090 return AKEY_STATE_UP;
4091 }
4092 }
4093
4094 return AKEY_STATE_UNKNOWN;
4095}
4096
4097int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4098 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4099 return AKEY_STATE_VIRTUAL;
4100 }
4101
4102 for (const VirtualKey& virtualKey : mVirtualKeys) {
4103 if (virtualKey.scanCode == scanCode) {
4104 return AKEY_STATE_UP;
4105 }
4106 }
4107
4108 return AKEY_STATE_UNKNOWN;
4109}
4110
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004111bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4112 const std::vector<int32_t>& keyCodes,
4113 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004114 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004115 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004116 if (virtualKey.keyCode == keyCodes[i]) {
4117 outFlags[i] = 1;
4118 }
4119 }
4120 }
4121
4122 return true;
4123}
4124
4125std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4126 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004127 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004128 return std::make_optional(mPointerController->getDisplayId());
4129 } else {
4130 return std::make_optional(mViewport.displayId);
4131 }
4132 }
4133 return std::nullopt;
4134}
4135
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004136} // namespace android