blob: 16bc381a9c38a3e6f53d22d1b1b42fe5b8a6b23e [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;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000900 } else {
901 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800903 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100905 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700906 if (hasStylus()) {
907 mSource |= AINPUT_SOURCE_STYLUS;
908 }
909 if (hasExternalStylus()) {
910 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
911 }
Michael Wright227c5542020-07-02 18:30:52 +0100912 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700913 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100914 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700915 } else {
916 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100917 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700918 }
919
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000920 const std::optional<DisplayViewport> newViewportOpt = findViewport();
921
922 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700923 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
924 ALOGW("Touch device '%s' did not report support for X or Y axis! "
925 "The device will be inoperable.",
926 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100927 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000928 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929 ALOGI("Touch device '%s' could not query the properties of its associated "
930 "display. The device will be inoperable until the display size "
931 "becomes available.",
932 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100933 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000934 } else if (!newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000935 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
936 getDeviceName().c_str(), getDeviceId());
937 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000938 }
939
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700940 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700941 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
942 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000943 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
944 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
945 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
946 const float rawMeanResolution =
947 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700948
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000949 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
950 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700951 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700952 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000953 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
954 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
955 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700956
Michael Wright227c5542020-07-02 18:30:52 +0100957 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700958 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700959 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
960 int32_t naturalPhysicalLeft, naturalPhysicalTop;
961 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700962
Prabir Pradhan1728b212021-10-19 16:00:03 -0700963 // Apply the inverse of the input device orientation so that the input device is
964 // configured in the same orientation as the viewport. The input device orientation will
965 // be re-applied by mInputDeviceOrientation.
966 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700967 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700968 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700969 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700970 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
971 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800972 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700973 naturalPhysicalTop = mViewport.physicalLeft;
974 naturalDeviceWidth = mViewport.deviceHeight;
975 naturalDeviceHeight = mViewport.deviceWidth;
976 break;
977 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700978 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
979 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
980 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
981 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
982 naturalDeviceWidth = mViewport.deviceWidth;
983 naturalDeviceHeight = mViewport.deviceHeight;
984 break;
985 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700986 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
987 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
988 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800989 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990 naturalDeviceWidth = mViewport.deviceHeight;
991 naturalDeviceHeight = mViewport.deviceWidth;
992 break;
993 case DISPLAY_ORIENTATION_0:
994 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700995 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
996 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
997 naturalPhysicalLeft = mViewport.physicalLeft;
998 naturalPhysicalTop = mViewport.physicalTop;
999 naturalDeviceWidth = mViewport.deviceWidth;
1000 naturalDeviceHeight = mViewport.deviceHeight;
1001 break;
1002 }
1003
1004 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
1005 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
1006 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
1007 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
1008 }
1009
1010 mPhysicalWidth = naturalPhysicalWidth;
1011 mPhysicalHeight = naturalPhysicalHeight;
1012 mPhysicalLeft = naturalPhysicalLeft;
1013 mPhysicalTop = naturalPhysicalTop;
1014
Prabir Pradhan1728b212021-10-19 16:00:03 -07001015 const int32_t oldDisplayWidth = mDisplayWidth;
1016 const int32_t oldDisplayHeight = mDisplayHeight;
1017 mDisplayWidth = naturalDeviceWidth;
1018 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -07001019
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001020 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1021 // anything if the device is already orientation-aware. If the device is not
1022 // orientation-aware, then we need to apply the inverse rotation of the display so that
1023 // when the display rotation is applied later as a part of the per-window transform, we
1024 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001025 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001026 ? DISPLAY_ORIENTATION_0
1027 : getInverseRotation(mViewport.orientation);
1028 // For orientation-aware devices that work in the un-rotated coordinate space, the
1029 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001030 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
1031 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
1032 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001033
1034 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001035 mInputDeviceOrientation =
1036 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001037 } else {
1038 mPhysicalWidth = rawWidth;
1039 mPhysicalHeight = rawHeight;
1040 mPhysicalLeft = 0;
1041 mPhysicalTop = 0;
1042
Prabir Pradhan1728b212021-10-19 16:00:03 -07001043 mDisplayWidth = rawWidth;
1044 mDisplayHeight = rawHeight;
1045 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001046 }
1047 }
1048
1049 // If moving between pointer modes, need to reset some state.
1050 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1051 if (deviceModeChanged) {
1052 mOrientedRanges.clear();
1053 }
1054
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001055 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
1056 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +01001057 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001058 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001059 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1060 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001061 if (mPointerController == nullptr) {
1062 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001063 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001064 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001065 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1066 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067 } else {
lilinnandef700b2022-06-17 19:32:01 +08001068 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1069 !mConfig.showTouches) {
1070 mPointerController->clearSpots();
1071 }
Michael Wright17db18e2020-06-26 20:51:44 +01001072 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001073 }
1074
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001075 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001076 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1077 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001078 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1079 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001080
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001081 configureVirtualKeys();
1082
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001083 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001084
1085 // Location
1086 updateAffineTransformation();
1087
Michael Wright227c5542020-07-02 18:30:52 +01001088 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001089 // Compute pointer gesture detection parameters.
1090 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001091 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092
1093 // Scale movements such that one whole swipe of the touch pad covers a
1094 // given area relative to the diagonal size of the display when no acceleration
1095 // is applied.
1096 // Assume that the touch pad has a square aspect ratio such that movements in
1097 // X and Y of the same number of raw units cover the same physical distance.
1098 mPointerXMovementScale =
1099 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1100 mPointerYMovementScale = mPointerXMovementScale;
1101
1102 // Scale zooms to cover a smaller range of the display than movements do.
1103 // This value determines the area around the pointer that is affected by freeform
1104 // pointer gestures.
1105 mPointerXZoomScale =
1106 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1107 mPointerYZoomScale = mPointerXZoomScale;
1108
HQ Liue6983c72022-04-19 22:14:56 +00001109 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1110 // axis is non positive value.
1111 const float minFreeformGestureWidth =
1112 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1113
1114 mPointerGestureMaxSwipeWidth =
1115 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1116 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 }
1118
1119 // Inform the dispatcher about the changes.
1120 *outResetNeeded = true;
1121 bumpGeneration();
1122 }
1123}
1124
Prabir Pradhan1728b212021-10-19 16:00:03 -07001125void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001127 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1128 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001129 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1130 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1131 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1132 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001133 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001134}
1135
1136void TouchInputMapper::configureVirtualKeys() {
1137 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001138 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139
1140 mVirtualKeys.clear();
1141
1142 if (virtualKeyDefinitions.size() == 0) {
1143 return;
1144 }
1145
1146 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1147 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1148 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1149 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1150
1151 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1152 VirtualKey virtualKey;
1153
1154 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1155 int32_t keyCode;
1156 int32_t dummyKeyMetaState;
1157 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001158 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1159 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1161 continue; // drop the key
1162 }
1163
1164 virtualKey.keyCode = keyCode;
1165 virtualKey.flags = flags;
1166
1167 // convert the key definition's display coordinates into touch coordinates for a hit box
1168 int32_t halfWidth = virtualKeyDefinition.width / 2;
1169 int32_t halfHeight = virtualKeyDefinition.height / 2;
1170
1171 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001172 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001173 touchScreenLeft;
1174 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001175 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001177 virtualKey.hitTop =
1178 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001180 virtualKey.hitBottom =
1181 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 touchScreenTop;
1183 mVirtualKeys.push_back(virtualKey);
1184 }
1185}
1186
1187void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1188 if (!mVirtualKeys.empty()) {
1189 dump += INDENT3 "Virtual Keys:\n";
1190
1191 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1192 const VirtualKey& virtualKey = mVirtualKeys[i];
1193 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1194 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1195 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1196 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1197 }
1198 }
1199}
1200
1201void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001202 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 Calibration& out = mCalibration;
1204
1205 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001207 std::string sizeCalibrationString;
1208 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001214 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001220 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 }
1222 }
1223
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001224 float sizeScale;
1225
1226 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1227 out.sizeScale = sizeScale;
1228 }
1229 float sizeBias;
1230 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1231 out.sizeBias = sizeBias;
1232 }
1233 bool sizeIsSummed;
1234 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1235 out.sizeIsSummed = sizeIsSummed;
1236 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237
1238 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001239 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001240 std::string pressureCalibrationString;
1241 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001243 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001245 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001247 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 } else if (pressureCalibrationString != "default") {
1249 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001250 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 }
1252 }
1253
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001254 float pressureScale;
1255 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1256 out.pressureScale = pressureScale;
1257 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258
1259 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001260 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001261 std::string orientationCalibrationString;
1262 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001264 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001266 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001268 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 } else if (orientationCalibrationString != "default") {
1270 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001271 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 }
1273 }
1274
1275 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001276 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001277 std::string distanceCalibrationString;
1278 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001280 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001282 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 } else if (distanceCalibrationString != "default") {
1284 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001285 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286 }
1287 }
1288
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001289 float distanceScale;
1290 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1291 out.distanceScale = distanceScale;
1292 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293
Michael Wright227c5542020-07-02 18:30:52 +01001294 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001295 std::string coverageCalibrationString;
1296 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001298 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001300 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 } else if (coverageCalibrationString != "default") {
1302 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001303 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 }
1305 }
1306}
1307
1308void TouchInputMapper::resolveCalibration() {
1309 // Size
1310 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001311 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1312 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 }
1314 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001315 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 }
1317
1318 // Pressure
1319 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001320 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1321 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 }
1323 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001324 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 }
1326
1327 // Orientation
1328 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001329 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1330 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 }
1332 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001333 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 }
1335
1336 // Distance
1337 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001338 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1339 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340 }
1341 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001342 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 }
1344
1345 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001346 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1347 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001348 }
1349}
1350
1351void TouchInputMapper::dumpCalibration(std::string& dump) {
1352 dump += INDENT3 "Calibration:\n";
1353
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001354 dump += INDENT4 "touch.size.calibration: ";
1355 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001357 if (mCalibration.sizeScale) {
1358 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001359 }
1360
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001361 if (mCalibration.sizeBias) {
1362 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001363 }
1364
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001365 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001367 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001368 }
1369
1370 // Pressure
1371 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001372 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001373 dump += INDENT4 "touch.pressure.calibration: none\n";
1374 break;
Michael Wright227c5542020-07-02 18:30:52 +01001375 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001376 dump += INDENT4 "touch.pressure.calibration: physical\n";
1377 break;
Michael Wright227c5542020-07-02 18:30:52 +01001378 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1380 break;
1381 default:
1382 ALOG_ASSERT(false);
1383 }
1384
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001385 if (mCalibration.pressureScale) {
1386 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001387 }
1388
1389 // Orientation
1390 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001391 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001392 dump += INDENT4 "touch.orientation.calibration: none\n";
1393 break;
Michael Wright227c5542020-07-02 18:30:52 +01001394 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001395 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1396 break;
Michael Wright227c5542020-07-02 18:30:52 +01001397 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001398 dump += INDENT4 "touch.orientation.calibration: vector\n";
1399 break;
1400 default:
1401 ALOG_ASSERT(false);
1402 }
1403
1404 // Distance
1405 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001406 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407 dump += INDENT4 "touch.distance.calibration: none\n";
1408 break;
Michael Wright227c5542020-07-02 18:30:52 +01001409 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410 dump += INDENT4 "touch.distance.calibration: scaled\n";
1411 break;
1412 default:
1413 ALOG_ASSERT(false);
1414 }
1415
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001416 if (mCalibration.distanceScale) {
1417 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001418 }
1419
1420 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001421 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422 dump += INDENT4 "touch.coverage.calibration: none\n";
1423 break;
Michael Wright227c5542020-07-02 18:30:52 +01001424 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001425 dump += INDENT4 "touch.coverage.calibration: box\n";
1426 break;
1427 default:
1428 ALOG_ASSERT(false);
1429 }
1430}
1431
1432void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1433 dump += INDENT3 "Affine Transformation:\n";
1434
1435 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1436 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1437 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1438 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1439 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1440 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1441}
1442
1443void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001444 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001445 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446}
1447
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001448std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001449 std::list<NotifyArgs> out = cancelTouch(when, when);
1450 updateTouchSpots();
1451
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001452 mCursorButtonAccumulator.reset(getDeviceContext());
1453 mCursorScrollAccumulator.reset(getDeviceContext());
1454 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455
1456 mPointerVelocityControl.reset();
1457 mWheelXVelocityControl.reset();
1458 mWheelYVelocityControl.reset();
1459
1460 mRawStatesPending.clear();
1461 mCurrentRawState.clear();
1462 mCurrentCookedState.clear();
1463 mLastRawState.clear();
1464 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001465 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001466 mSentHoverEnter = false;
1467 mHavePointerIds = false;
1468 mCurrentMotionAborted = false;
1469 mDownTime = 0;
1470
1471 mCurrentVirtualKey.down = false;
1472
1473 mPointerGesture.reset();
1474 mPointerSimple.reset();
1475 resetExternalStylus();
1476
1477 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001478 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479 mPointerController->clearSpots();
1480 }
1481
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001482 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001483}
1484
1485void TouchInputMapper::resetExternalStylus() {
1486 mExternalStylusState.clear();
1487 mExternalStylusId = -1;
1488 mExternalStylusFusionTimeout = LLONG_MAX;
1489 mExternalStylusDataPending = false;
1490}
1491
1492void TouchInputMapper::clearStylusDataPendingFlags() {
1493 mExternalStylusDataPending = false;
1494 mExternalStylusFusionTimeout = LLONG_MAX;
1495}
1496
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001497std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498 mCursorButtonAccumulator.process(rawEvent);
1499 mCursorScrollAccumulator.process(rawEvent);
1500 mTouchButtonAccumulator.process(rawEvent);
1501
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001502 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001503 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001504 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001505 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001506 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001507}
1508
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001509std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1510 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001511 if (mDeviceMode == DeviceMode::DISABLED) {
1512 // Only save the last pending state when the device is disabled.
1513 mRawStatesPending.clear();
1514 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001515 // Push a new state.
1516 mRawStatesPending.emplace_back();
1517
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001518 RawState& next = mRawStatesPending.back();
1519 next.clear();
1520 next.when = when;
1521 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522
1523 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001524 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001525 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1526
1527 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001528 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1529 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001530 mCursorScrollAccumulator.finishSync();
1531
1532 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001533 syncTouch(when, &next);
1534
1535 // The last RawState is the actually second to last, since we just added a new state
1536 const RawState& last =
1537 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001538
1539 // Assign pointer ids.
1540 if (!mHavePointerIds) {
1541 assignPointerIds(last, next);
1542 }
1543
Harry Cutts45483602022-08-24 14:36:48 +00001544 ALOGD_IF(DEBUG_RAW_EVENTS,
1545 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1546 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1547 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1548 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1549 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1550 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001551
Arthur Hung9ad18942021-06-19 02:04:46 +00001552 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1553 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1554 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1555 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1556 next.rawPointerData.hoveringIdBits.value);
1557 }
1558
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001559 out += processRawTouches(false /*timeout*/);
1560 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001561}
1562
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001563std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1564 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001565 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001566 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001567 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001568 }
1569
1570 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1571 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1572 // touching the current state will only observe the events that have been dispatched to the
1573 // rest of the pipeline.
1574 const size_t N = mRawStatesPending.size();
1575 size_t count;
1576 for (count = 0; count < N; count++) {
1577 const RawState& next = mRawStatesPending[count];
1578
1579 // A failure to assign the stylus id means that we're waiting on stylus data
1580 // and so should defer the rest of the pipeline.
1581 if (assignExternalStylusId(next, timeout)) {
1582 break;
1583 }
1584
1585 // All ready to go.
1586 clearStylusDataPendingFlags();
1587 mCurrentRawState.copyFrom(next);
1588 if (mCurrentRawState.when < mLastRawState.when) {
1589 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001590 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001592 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001593 }
1594 if (count != 0) {
1595 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1596 }
1597
1598 if (mExternalStylusDataPending) {
1599 if (timeout) {
1600 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1601 clearStylusDataPendingFlags();
1602 mCurrentRawState.copyFrom(mLastRawState);
Harry Cutts45483602022-08-24 14:36:48 +00001603 ALOGD_IF(DEBUG_STYLUS_FUSION,
1604 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001605 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001606 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001607 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1608 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1609 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1610 }
1611 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001612 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001613}
1614
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001615std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1616 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617 // Always start with a clean state.
1618 mCurrentCookedState.clear();
1619
1620 // Apply stylus buttons to current raw state.
1621 applyExternalStylusButtonState(when);
1622
1623 // Handle policy on initial down or hover events.
1624 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1625 mCurrentRawState.rawPointerData.pointerCount != 0;
1626
1627 uint32_t policyFlags = 0;
1628 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1629 if (initialDown || buttonsPressed) {
1630 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001631 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 getContext()->fadePointer();
1633 }
1634
1635 if (mParameters.wake) {
1636 policyFlags |= POLICY_FLAG_WAKE;
1637 }
1638 }
1639
1640 // Consume raw off-screen touches before cooking pointer data.
1641 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001642 bool consumed;
1643 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1644 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001645 mCurrentRawState.rawPointerData.clear();
1646 }
1647
1648 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1649 // with cooked pointer data that has the same ids and indices as the raw data.
1650 // The following code can use either the raw or cooked data, as needed.
1651 cookPointerData();
1652
1653 // Apply stylus pressure to current cooked state.
1654 applyExternalStylusTouchState(when);
1655
1656 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001657 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1658 mSource, mViewport.displayId, policyFlags,
1659 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001660
1661 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001662 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001663 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1664 uint32_t id = idBits.clearFirstMarkedBit();
1665 const RawPointerData::Pointer& pointer =
1666 mCurrentRawState.rawPointerData.pointerForId(id);
1667 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1668 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1669 mCurrentCookedState.stylusIdBits.markBit(id);
1670 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1671 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1672 mCurrentCookedState.fingerIdBits.markBit(id);
1673 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1674 mCurrentCookedState.mouseIdBits.markBit(id);
1675 }
1676 }
1677 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1678 uint32_t id = idBits.clearFirstMarkedBit();
1679 const RawPointerData::Pointer& pointer =
1680 mCurrentRawState.rawPointerData.pointerForId(id);
1681 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1682 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1683 mCurrentCookedState.stylusIdBits.markBit(id);
1684 }
1685 }
1686
1687 // Stylus takes precedence over all tools, then mouse, then finger.
1688 PointerUsage pointerUsage = mPointerUsage;
1689 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1690 mCurrentCookedState.mouseIdBits.clear();
1691 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001692 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001693 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1694 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001695 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001696 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1697 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001698 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001699 }
1700
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001701 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001702 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001703 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001704 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001705 out += dispatchButtonRelease(when, readTime, policyFlags);
1706 out += dispatchHoverExit(when, readTime, policyFlags);
1707 out += dispatchTouches(when, readTime, policyFlags);
1708 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1709 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001710 }
1711
1712 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1713 mCurrentMotionAborted = false;
1714 }
1715 }
1716
1717 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001718 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1719 mSource, mViewport.displayId, policyFlags,
1720 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001721
1722 // Clear some transient state.
1723 mCurrentRawState.rawVScroll = 0;
1724 mCurrentRawState.rawHScroll = 0;
1725
1726 // Copy current touch to last touch in preparation for the next cycle.
1727 mLastRawState.copyFrom(mCurrentRawState);
1728 mLastCookedState.copyFrom(mCurrentCookedState);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001729 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001730}
1731
Garfield Tanc734e4f2021-01-15 20:01:39 -08001732void TouchInputMapper::updateTouchSpots() {
1733 if (!mConfig.showTouches || mPointerController == nullptr) {
1734 return;
1735 }
1736
1737 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1738 // clear touch spots.
1739 if (mDeviceMode != DeviceMode::DIRECT &&
1740 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1741 return;
1742 }
1743
1744 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1745 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1746
1747 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001748 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1749 mCurrentCookedState.cookedPointerData.idToIndex,
1750 mCurrentCookedState.cookedPointerData.touchingIdBits,
1751 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001752}
1753
1754bool TouchInputMapper::isTouchScreen() {
1755 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1756 mParameters.hasAssociatedDisplay;
1757}
1758
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001759void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001760 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001761 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1762 }
1763}
1764
1765void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1766 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1767 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1768
1769 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1770 float pressure = mExternalStylusState.pressure;
1771 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1772 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1773 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1774 }
1775 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1776 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1777
1778 PointerProperties& properties =
1779 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1780 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1781 properties.toolType = mExternalStylusState.toolType;
1782 }
1783 }
1784}
1785
1786bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001787 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001788 return false;
1789 }
1790
1791 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1792 state.rawPointerData.pointerCount != 0;
1793 if (initialDown) {
1794 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001795 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001796 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1797 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001798 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001799 resetExternalStylus();
1800 } else {
1801 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1802 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1803 }
Harry Cutts45483602022-08-24 14:36:48 +00001804 ALOGD_IF(DEBUG_STYLUS_FUSION,
1805 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1806 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001807 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1808 return true;
1809 }
1810 }
1811
1812 // Check if the stylus pointer has gone up.
1813 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001814 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001815 mExternalStylusId = -1;
1816 }
1817
1818 return false;
1819}
1820
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001821std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1822 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001823 if (mDeviceMode == DeviceMode::POINTER) {
1824 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001825 // Since this is a synthetic event, we can consider its latency to be zero
1826 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001827 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001828 }
Michael Wright227c5542020-07-02 18:30:52 +01001829 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001830 if (mExternalStylusFusionTimeout < when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001831 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001832 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1833 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1834 }
1835 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001836 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001837}
1838
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001839std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1840 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001841 mExternalStylusState.copyFrom(state);
1842 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1843 // We're either in the middle of a fused stream of data or we're waiting on data before
1844 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1845 // data.
1846 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001847 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001848 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001849 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001850}
1851
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001852std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1853 uint32_t policyFlags, bool& outConsumed) {
1854 outConsumed = false;
1855 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001856 // Check for release of a virtual key.
1857 if (mCurrentVirtualKey.down) {
1858 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1859 // Pointer went up while virtual key was down.
1860 mCurrentVirtualKey.down = false;
1861 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001862 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1863 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1864 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001865 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1866 AKEY_EVENT_FLAG_FROM_SYSTEM |
1867 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001868 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001869 outConsumed = true;
1870 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001871 }
1872
1873 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1874 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1875 const RawPointerData::Pointer& pointer =
1876 mCurrentRawState.rawPointerData.pointerForId(id);
1877 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1878 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1879 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001880 outConsumed = true;
1881 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001882 }
1883 }
1884
1885 // Pointer left virtual key area or another pointer also went down.
1886 // Send key cancellation but do not consume the touch yet.
1887 // This is useful when the user swipes through from the virtual key area
1888 // into the main display surface.
1889 mCurrentVirtualKey.down = false;
1890 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001891 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1892 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001893 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1894 AKEY_EVENT_FLAG_FROM_SYSTEM |
1895 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1896 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001897 }
1898 }
1899
1900 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1901 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1902 // Pointer just went down. Check for virtual key press or off-screen touches.
1903 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1904 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001905 // Skip checking whether the pointer is inside the physical frame if the device is in
1906 // unscaled mode.
1907 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1908 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001909 // If exactly one pointer went down, check for virtual key hit.
1910 // Otherwise we will drop the entire stroke.
1911 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1912 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1913 if (virtualKey) {
1914 mCurrentVirtualKey.down = true;
1915 mCurrentVirtualKey.downTime = when;
1916 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1917 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1918 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001919 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1920 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921
1922 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001923 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1924 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1925 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001926 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1927 AKEY_EVENT_ACTION_DOWN,
1928 AKEY_EVENT_FLAG_FROM_SYSTEM |
1929 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001930 }
1931 }
1932 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001933 outConsumed = true;
1934 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001935 }
1936 }
1937
1938 // Disable all virtual key touches that happen within a short time interval of the
1939 // most recent touch within the screen area. The idea is to filter out stray
1940 // virtual key presses when interacting with the touch screen.
1941 //
1942 // Problems we're trying to solve:
1943 //
1944 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1945 // virtual key area that is implemented by a separate touch panel and accidentally
1946 // triggers a virtual key.
1947 //
1948 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1949 // area and accidentally triggers a virtual key. This often happens when virtual keys
1950 // are layed out below the screen near to where the on screen keyboard's space bar
1951 // is displayed.
1952 if (mConfig.virtualKeyQuietTime > 0 &&
1953 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001954 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001955 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001956 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001957}
1958
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001959NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1960 uint32_t policyFlags, int32_t keyEventAction,
1961 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001962 int32_t keyCode = mCurrentVirtualKey.keyCode;
1963 int32_t scanCode = mCurrentVirtualKey.scanCode;
1964 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001965 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001966 policyFlags |= POLICY_FLAG_VIRTUAL;
1967
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001968 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1969 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1970 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001971}
1972
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001973std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1974 uint32_t policyFlags) {
1975 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001976 if (mCurrentMotionAborted) {
1977 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001978 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001979 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001980 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1981 if (!currentIdBits.isEmpty()) {
1982 int32_t metaState = getContext()->getGlobalMetaState();
1983 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001984 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001985 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1986 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001987 mCurrentCookedState.cookedPointerData.pointerProperties,
1988 mCurrentCookedState.cookedPointerData.pointerCoords,
1989 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1990 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1991 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001992 mCurrentMotionAborted = true;
1993 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001994 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001995}
1996
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001997std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1998 uint32_t policyFlags) {
1999 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002000 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2001 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2002 int32_t metaState = getContext()->getGlobalMetaState();
2003 int32_t buttonState = mCurrentCookedState.buttonState;
2004
2005 if (currentIdBits == lastIdBits) {
2006 if (!currentIdBits.isEmpty()) {
2007 // No pointer id changes so this is a move event.
2008 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002009 out.push_back(
2010 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2011 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2012 mCurrentCookedState.cookedPointerData.pointerProperties,
2013 mCurrentCookedState.cookedPointerData.pointerCoords,
2014 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2015 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2016 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002017 }
2018 } else {
2019 // There may be pointers going up and pointers going down and pointers moving
2020 // all at the same time.
2021 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2022 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2023 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2024 BitSet32 dispatchedIdBits(lastIdBits.value);
2025
2026 // Update last coordinates of pointers that have moved so that we observe the new
2027 // pointer positions at the same time as other pointers that have just gone up.
2028 bool moveNeeded =
2029 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2030 mCurrentCookedState.cookedPointerData.pointerCoords,
2031 mCurrentCookedState.cookedPointerData.idToIndex,
2032 mLastCookedState.cookedPointerData.pointerProperties,
2033 mLastCookedState.cookedPointerData.pointerCoords,
2034 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2035 if (buttonState != mLastCookedState.buttonState) {
2036 moveNeeded = true;
2037 }
2038
2039 // Dispatch pointer up events.
2040 while (!upIdBits.isEmpty()) {
2041 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002042 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002043 if (isCanceled) {
2044 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2045 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002046 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2047 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2048 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2049 buttonState, 0,
2050 mLastCookedState.cookedPointerData.pointerProperties,
2051 mLastCookedState.cookedPointerData.pointerCoords,
2052 mLastCookedState.cookedPointerData.idToIndex,
2053 dispatchedIdBits, upId, mOrientedXPrecision,
2054 mOrientedYPrecision, mDownTime,
2055 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002056 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002057 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002058 }
2059
2060 // Dispatch move events if any of the remaining pointers moved from their old locations.
2061 // Although applications receive new locations as part of individual pointer up
2062 // events, they do not generally handle them except when presented in a move event.
2063 if (moveNeeded && !moveIdBits.isEmpty()) {
2064 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002065 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2066 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2067 mCurrentCookedState.cookedPointerData.pointerProperties,
2068 mCurrentCookedState.cookedPointerData.pointerCoords,
2069 mCurrentCookedState.cookedPointerData.idToIndex,
2070 dispatchedIdBits, -1, mOrientedXPrecision,
2071 mOrientedYPrecision, mDownTime,
2072 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002073 }
2074
2075 // Dispatch pointer down events using the new pointer locations.
2076 while (!downIdBits.isEmpty()) {
2077 uint32_t downId = downIdBits.clearFirstMarkedBit();
2078 dispatchedIdBits.markBit(downId);
2079
2080 if (dispatchedIdBits.count() == 1) {
2081 // First pointer is going down. Set down time.
2082 mDownTime = when;
2083 }
2084
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002085 out.push_back(
2086 dispatchMotion(when, readTime, policyFlags, mSource,
2087 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2088 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2089 mCurrentCookedState.cookedPointerData.pointerCoords,
2090 mCurrentCookedState.cookedPointerData.idToIndex,
2091 dispatchedIdBits, downId, mOrientedXPrecision,
2092 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002093 }
2094 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002095 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002096}
2097
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002098std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2099 uint32_t policyFlags) {
2100 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002101 if (mSentHoverEnter &&
2102 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2103 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2104 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002105 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2106 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2107 mLastCookedState.buttonState, 0,
2108 mLastCookedState.cookedPointerData.pointerProperties,
2109 mLastCookedState.cookedPointerData.pointerCoords,
2110 mLastCookedState.cookedPointerData.idToIndex,
2111 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2112 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2113 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002114 mSentHoverEnter = false;
2115 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002116 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002117}
2118
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002119std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2120 uint32_t policyFlags) {
2121 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002122 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2123 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2124 int32_t metaState = getContext()->getGlobalMetaState();
2125 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002126 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2127 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2128 mCurrentRawState.buttonState, 0,
2129 mCurrentCookedState.cookedPointerData.pointerProperties,
2130 mCurrentCookedState.cookedPointerData.pointerCoords,
2131 mCurrentCookedState.cookedPointerData.idToIndex,
2132 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2133 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2134 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002135 mSentHoverEnter = true;
2136 }
2137
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002138 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2139 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2140 mCurrentRawState.buttonState, 0,
2141 mCurrentCookedState.cookedPointerData.pointerProperties,
2142 mCurrentCookedState.cookedPointerData.pointerCoords,
2143 mCurrentCookedState.cookedPointerData.idToIndex,
2144 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2145 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2146 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002147 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002148 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002149}
2150
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002151std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2152 uint32_t policyFlags) {
2153 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2155 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2156 const int32_t metaState = getContext()->getGlobalMetaState();
2157 int32_t buttonState = mLastCookedState.buttonState;
2158 while (!releasedButtons.isEmpty()) {
2159 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2160 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002161 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2162 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2163 metaState, buttonState, 0,
2164 mCurrentCookedState.cookedPointerData.pointerProperties,
2165 mCurrentCookedState.cookedPointerData.pointerCoords,
2166 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2167 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2168 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002169 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002170 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002171}
2172
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002173std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2174 uint32_t policyFlags) {
2175 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002176 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2177 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2178 const int32_t metaState = getContext()->getGlobalMetaState();
2179 int32_t buttonState = mLastCookedState.buttonState;
2180 while (!pressedButtons.isEmpty()) {
2181 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2182 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002183 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2184 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2185 buttonState, 0,
2186 mCurrentCookedState.cookedPointerData.pointerProperties,
2187 mCurrentCookedState.cookedPointerData.pointerCoords,
2188 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2189 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2190 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002191 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002192 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002193}
2194
2195const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2196 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2197 return cookedPointerData.touchingIdBits;
2198 }
2199 return cookedPointerData.hoveringIdBits;
2200}
2201
2202void TouchInputMapper::cookPointerData() {
2203 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2204
2205 mCurrentCookedState.cookedPointerData.clear();
2206 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2207 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2208 mCurrentRawState.rawPointerData.hoveringIdBits;
2209 mCurrentCookedState.cookedPointerData.touchingIdBits =
2210 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002211 mCurrentCookedState.cookedPointerData.canceledIdBits =
2212 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002213
2214 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2215 mCurrentCookedState.buttonState = 0;
2216 } else {
2217 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2218 }
2219
2220 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002221 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002222 for (uint32_t i = 0; i < currentPointerCount; i++) {
2223 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2224
2225 // Size
2226 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2227 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002228 case Calibration::SizeCalibration::GEOMETRIC:
2229 case Calibration::SizeCalibration::DIAMETER:
2230 case Calibration::SizeCalibration::BOX:
2231 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002232 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2233 touchMajor = in.touchMajor;
2234 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2235 toolMajor = in.toolMajor;
2236 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2237 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2238 : in.touchMajor;
2239 } else if (mRawPointerAxes.touchMajor.valid) {
2240 toolMajor = touchMajor = in.touchMajor;
2241 toolMinor = touchMinor =
2242 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2243 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2244 : in.touchMajor;
2245 } else if (mRawPointerAxes.toolMajor.valid) {
2246 touchMajor = toolMajor = in.toolMajor;
2247 touchMinor = toolMinor =
2248 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2249 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2250 : in.toolMajor;
2251 } else {
2252 ALOG_ASSERT(false,
2253 "No touch or tool axes. "
2254 "Size calibration should have been resolved to NONE.");
2255 touchMajor = 0;
2256 touchMinor = 0;
2257 toolMajor = 0;
2258 toolMinor = 0;
2259 size = 0;
2260 }
2261
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002262 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002263 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2264 if (touchingCount > 1) {
2265 touchMajor /= touchingCount;
2266 touchMinor /= touchingCount;
2267 toolMajor /= touchingCount;
2268 toolMinor /= touchingCount;
2269 size /= touchingCount;
2270 }
2271 }
2272
Michael Wright227c5542020-07-02 18:30:52 +01002273 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002274 touchMajor *= mGeometricScale;
2275 touchMinor *= mGeometricScale;
2276 toolMajor *= mGeometricScale;
2277 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002278 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002279 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2280 touchMinor = touchMajor;
2281 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2282 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002283 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002284 touchMinor = touchMajor;
2285 toolMinor = toolMajor;
2286 }
2287
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002288 mCalibration.applySizeScaleAndBias(touchMajor);
2289 mCalibration.applySizeScaleAndBias(touchMinor);
2290 mCalibration.applySizeScaleAndBias(toolMajor);
2291 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 size *= mSizeScale;
2293 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002294 case Calibration::SizeCalibration::DEFAULT:
2295 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2296 break;
2297 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002298 touchMajor = 0;
2299 touchMinor = 0;
2300 toolMajor = 0;
2301 toolMinor = 0;
2302 size = 0;
2303 break;
2304 }
2305
2306 // Pressure
2307 float pressure;
2308 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002309 case Calibration::PressureCalibration::PHYSICAL:
2310 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002311 pressure = in.pressure * mPressureScale;
2312 break;
2313 default:
2314 pressure = in.isHovering ? 0 : 1;
2315 break;
2316 }
2317
2318 // Tilt and Orientation
2319 float tilt;
2320 float orientation;
2321 if (mHaveTilt) {
2322 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2323 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2324 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2325 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2326 } else {
2327 tilt = 0;
2328
2329 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002330 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002331 orientation = in.orientation * mOrientationScale;
2332 break;
Michael Wright227c5542020-07-02 18:30:52 +01002333 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002334 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2335 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2336 if (c1 != 0 || c2 != 0) {
2337 orientation = atan2f(c1, c2) * 0.5f;
2338 float confidence = hypotf(c1, c2);
2339 float scale = 1.0f + confidence / 16.0f;
2340 touchMajor *= scale;
2341 touchMinor /= scale;
2342 toolMajor *= scale;
2343 toolMinor /= scale;
2344 } else {
2345 orientation = 0;
2346 }
2347 break;
2348 }
2349 default:
2350 orientation = 0;
2351 }
2352 }
2353
2354 // Distance
2355 float distance;
2356 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002357 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 distance = in.distance * mDistanceScale;
2359 break;
2360 default:
2361 distance = 0;
2362 }
2363
2364 // Coverage
2365 int32_t rawLeft, rawTop, rawRight, rawBottom;
2366 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002367 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2369 rawRight = in.toolMinor & 0x0000ffff;
2370 rawBottom = in.toolMajor & 0x0000ffff;
2371 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2372 break;
2373 default:
2374 rawLeft = rawTop = rawRight = rawBottom = 0;
2375 break;
2376 }
2377
2378 // Adjust X,Y coords for device calibration
2379 // TODO: Adjust coverage coords?
2380 float xTransformed = in.x, yTransformed = in.y;
2381 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002382 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383
Prabir Pradhan1728b212021-10-19 16:00:03 -07002384 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 float left, top, right, bottom;
2386
Prabir Pradhan1728b212021-10-19 16:00:03 -07002387 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002389 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2390 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2391 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2392 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002394 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002395 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002396 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 }
2398 break;
2399 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2401 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002402 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2403 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002405 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002407 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002408 }
2409 break;
2410 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2412 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002413 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2414 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002416 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002418 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 }
2420 break;
2421 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002422 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2423 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2424 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2425 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 break;
2427 }
2428
2429 // Write output coords.
2430 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2431 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002432 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2433 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2435 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2436 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2437 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2438 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2439 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2440 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002441 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2443 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2444 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2445 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2446 } else {
2447 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2448 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2449 }
2450
Chris Ye364fdb52020-08-05 15:07:56 -07002451 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002452 uint32_t id = in.id;
2453 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2454 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2455 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2456 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2457 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2458 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2459 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2460 }
2461
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462 // Write output properties.
2463 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 properties.clear();
2465 properties.id = id;
2466 properties.toolType = in.toolType;
2467
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002468 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002470 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002471 }
2472}
2473
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002474std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2475 uint32_t policyFlags,
2476 PointerUsage pointerUsage) {
2477 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002479 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 mPointerUsage = pointerUsage;
2481 }
2482
2483 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002484 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002485 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 break;
Michael Wright227c5542020-07-02 18:30:52 +01002487 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002488 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002489 break;
Michael Wright227c5542020-07-02 18:30:52 +01002490 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002491 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002492 break;
Michael Wright227c5542020-07-02 18:30:52 +01002493 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 break;
2495 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002496 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497}
2498
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002499std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2500 uint32_t policyFlags) {
2501 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002503 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002504 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002505 break;
Michael Wright227c5542020-07-02 18:30:52 +01002506 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002507 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002508 break;
Michael Wright227c5542020-07-02 18:30:52 +01002509 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002510 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 break;
Michael Wright227c5542020-07-02 18:30:52 +01002512 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002513 break;
2514 }
2515
Michael Wright227c5542020-07-02 18:30:52 +01002516 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002517 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002518}
2519
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002520std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2521 uint32_t policyFlags,
2522 bool isTimeout) {
2523 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 // Update current gesture coordinates.
2525 bool cancelPreviousGesture, finishPreviousGesture;
2526 bool sendEvents =
2527 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2528 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002529 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002530 }
2531 if (finishPreviousGesture) {
2532 cancelPreviousGesture = false;
2533 }
2534
2535 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002536 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002537 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002538 if (finishPreviousGesture || cancelPreviousGesture) {
2539 mPointerController->clearSpots();
2540 }
2541
Michael Wright227c5542020-07-02 18:30:52 +01002542 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002543 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2544 mPointerGesture.currentGestureIdToIndex,
2545 mPointerGesture.currentGestureIdBits,
2546 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002547 }
2548 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002549 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002550 }
2551
2552 // Show or hide the pointer if needed.
2553 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002554 case PointerGesture::Mode::NEUTRAL:
2555 case PointerGesture::Mode::QUIET:
2556 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2557 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002558 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002559 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002560 }
2561 break;
Michael Wright227c5542020-07-02 18:30:52 +01002562 case PointerGesture::Mode::TAP:
2563 case PointerGesture::Mode::TAP_DRAG:
2564 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2565 case PointerGesture::Mode::HOVER:
2566 case PointerGesture::Mode::PRESS:
2567 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002568 // Unfade the pointer when the current gesture manipulates the
2569 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002570 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002571 break;
Michael Wright227c5542020-07-02 18:30:52 +01002572 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002573 // Fade the pointer when the current gesture manipulates a different
2574 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002575 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002576 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002577 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002578 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002579 }
2580 break;
2581 }
2582
2583 // Send events!
2584 int32_t metaState = getContext()->getGlobalMetaState();
2585 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002586 const MotionClassification classification =
2587 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2588 ? MotionClassification::TWO_FINGER_SWIPE
2589 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002590
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002591 uint32_t flags = 0;
2592
2593 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2594 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2595 }
2596
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002597 // Update last coordinates of pointers that have moved so that we observe the new
2598 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002599 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2600 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2601 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2602 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2603 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2604 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002605 bool moveNeeded = false;
2606 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2607 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2608 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2609 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2610 mPointerGesture.lastGestureIdBits.value);
2611 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2612 mPointerGesture.currentGestureCoords,
2613 mPointerGesture.currentGestureIdToIndex,
2614 mPointerGesture.lastGestureProperties,
2615 mPointerGesture.lastGestureCoords,
2616 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2617 if (buttonState != mLastCookedState.buttonState) {
2618 moveNeeded = true;
2619 }
2620 }
2621
2622 // Send motion events for all pointers that went up or were canceled.
2623 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2624 if (!dispatchedGestureIdBits.isEmpty()) {
2625 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002626 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002627 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002628 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002629 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2630 mPointerGesture.lastGestureProperties,
2631 mPointerGesture.lastGestureCoords,
2632 mPointerGesture.lastGestureIdToIndex,
2633 dispatchedGestureIdBits, -1, 0, 0,
2634 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002635
2636 dispatchedGestureIdBits.clear();
2637 } else {
2638 BitSet32 upGestureIdBits;
2639 if (finishPreviousGesture) {
2640 upGestureIdBits = dispatchedGestureIdBits;
2641 } else {
2642 upGestureIdBits.value =
2643 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2644 }
2645 while (!upGestureIdBits.isEmpty()) {
2646 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2647
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002648 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2649 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2650 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2651 mPointerGesture.lastGestureProperties,
2652 mPointerGesture.lastGestureCoords,
2653 mPointerGesture.lastGestureIdToIndex,
2654 dispatchedGestureIdBits, id, 0, 0,
2655 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002656
2657 dispatchedGestureIdBits.clearBit(id);
2658 }
2659 }
2660 }
2661
2662 // Send motion events for all pointers that moved.
2663 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002664 out.push_back(
2665 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2666 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2667 mPointerGesture.currentGestureProperties,
2668 mPointerGesture.currentGestureCoords,
2669 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2670 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002671 }
2672
2673 // Send motion events for all pointers that went down.
2674 if (down) {
2675 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2676 ~dispatchedGestureIdBits.value);
2677 while (!downGestureIdBits.isEmpty()) {
2678 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2679 dispatchedGestureIdBits.markBit(id);
2680
2681 if (dispatchedGestureIdBits.count() == 1) {
2682 mPointerGesture.downTime = when;
2683 }
2684
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002685 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2686 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2687 buttonState, 0, mPointerGesture.currentGestureProperties,
2688 mPointerGesture.currentGestureCoords,
2689 mPointerGesture.currentGestureIdToIndex,
2690 dispatchedGestureIdBits, id, 0, 0,
2691 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002692 }
2693 }
2694
2695 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002696 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002697 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2698 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2699 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2700 mPointerGesture.currentGestureProperties,
2701 mPointerGesture.currentGestureCoords,
2702 mPointerGesture.currentGestureIdToIndex,
2703 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2704 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002705 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2706 // Synthesize a hover move event after all pointers go up to indicate that
2707 // the pointer is hovering again even if the user is not currently touching
2708 // the touch pad. This ensures that a view will receive a fresh hover enter
2709 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002710 float x, y;
2711 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002712
2713 PointerProperties pointerProperties;
2714 pointerProperties.clear();
2715 pointerProperties.id = 0;
2716 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2717
2718 PointerCoords pointerCoords;
2719 pointerCoords.clear();
2720 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2721 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2722
2723 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002724 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2725 mSource, displayId, policyFlags,
2726 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2727 buttonState, MotionClassification::NONE,
2728 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2729 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2730 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002731 }
2732
2733 // Update state.
2734 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2735 if (!down) {
2736 mPointerGesture.lastGestureIdBits.clear();
2737 } else {
2738 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2739 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2740 uint32_t id = idBits.clearFirstMarkedBit();
2741 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2742 mPointerGesture.lastGestureProperties[index].copyFrom(
2743 mPointerGesture.currentGestureProperties[index]);
2744 mPointerGesture.lastGestureCoords[index].copyFrom(
2745 mPointerGesture.currentGestureCoords[index]);
2746 mPointerGesture.lastGestureIdToIndex[id] = index;
2747 }
2748 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002749 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002750}
2751
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002752std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2753 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002754 const MotionClassification classification =
2755 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2756 ? MotionClassification::TWO_FINGER_SWIPE
2757 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002758 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002759 // Cancel previously dispatches pointers.
2760 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2761 int32_t metaState = getContext()->getGlobalMetaState();
2762 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002763 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002764 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2765 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002766 mPointerGesture.lastGestureProperties,
2767 mPointerGesture.lastGestureCoords,
2768 mPointerGesture.lastGestureIdToIndex,
2769 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2770 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002771 }
2772
2773 // Reset the current pointer gesture.
2774 mPointerGesture.reset();
2775 mPointerVelocityControl.reset();
2776
2777 // Remove any current spots.
2778 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002779 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002780 mPointerController->clearSpots();
2781 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002782 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002783}
2784
2785bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2786 bool* outFinishPreviousGesture, bool isTimeout) {
2787 *outCancelPreviousGesture = false;
2788 *outFinishPreviousGesture = false;
2789
2790 // Handle TAP timeout.
2791 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002792 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002793
Michael Wright227c5542020-07-02 18:30:52 +01002794 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2796 // The tap/drag timeout has not yet expired.
2797 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2798 mConfig.pointerGestureTapDragInterval);
2799 } else {
2800 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002801 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002802 *outFinishPreviousGesture = true;
2803
2804 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002805 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 mPointerGesture.currentGestureIdBits.clear();
2807
2808 mPointerVelocityControl.reset();
2809 return true;
2810 }
2811 }
2812
2813 // We did not handle this timeout.
2814 return false;
2815 }
2816
2817 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2818 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2819
2820 // Update the velocity tracker.
2821 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002822 std::vector<float> positionsX;
2823 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002824 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825 uint32_t id = idBits.clearFirstMarkedBit();
2826 const RawPointerData::Pointer& pointer =
2827 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002828 positionsX.push_back(pointer.x * mPointerXMovementScale);
2829 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 }
2831 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002832 {{AMOTION_EVENT_AXIS_X, positionsX},
2833 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002834 }
2835
2836 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2837 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002838 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2839 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2840 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002841 mPointerGesture.resetTap();
2842 }
2843
2844 // Pick a new active touch id if needed.
2845 // Choose an arbitrary pointer that just went down, if there is one.
2846 // Otherwise choose an arbitrary remaining pointer.
2847 // This guarantees we always have an active touch id when there is at least one pointer.
2848 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002849 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002850 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002851 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002852 mPointerGesture.firstTouchTime = when;
2853 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002854 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2855 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2856 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2857 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002858 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002859 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002860
2861 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002862 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002863 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002864 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2865 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2866 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002867 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002868 *outFinishPreviousGesture = true;
2869 }
2870
2871 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002872 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 mPointerGesture.currentGestureIdBits.clear();
2874
2875 mPointerVelocityControl.reset();
2876 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2877 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2878 // The pointer follows the active touch point.
2879 // Emit DOWN, MOVE, UP events at the pointer location.
2880 //
2881 // Only the active touch matters; other fingers are ignored. This policy helps
2882 // to handle the case where the user places a second finger on the touch pad
2883 // to apply the necessary force to depress an integrated button below the surface.
2884 // We don't want the second finger to be delivered to applications.
2885 //
2886 // For this to work well, we need to make sure to track the pointer that is really
2887 // active. If the user first puts one finger down to click then adds another
2888 // finger to drag then the active pointer should switch to the finger that is
2889 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002890 ALOGD_IF(DEBUG_GESTURES,
2891 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2892 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002893 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002894 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 *outFinishPreviousGesture = true;
2896 mPointerGesture.activeGestureId = 0;
2897 }
2898
2899 // Switch pointers if needed.
2900 // Find the fastest pointer and follow it.
2901 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002902 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002904 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002905 ALOGD_IF(DEBUG_GESTURES,
2906 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2907 "bestSpeed=%0.3f",
2908 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002909 }
2910 }
2911
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002912 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913 // When using spots, the click will occur at the position of the anchor
2914 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002915 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916 } else {
2917 mPointerVelocityControl.reset();
2918 }
2919
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002920 float x, y;
2921 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922
Michael Wright227c5542020-07-02 18:30:52 +01002923 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002924 mPointerGesture.currentGestureIdBits.clear();
2925 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2926 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2927 mPointerGesture.currentGestureProperties[0].clear();
2928 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2929 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2930 mPointerGesture.currentGestureCoords[0].clear();
2931 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2932 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2933 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2934 } else if (currentFingerCount == 0) {
2935 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002936 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002937 *outFinishPreviousGesture = true;
2938 }
2939
2940 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2941 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2942 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002943 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2944 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 lastFingerCount == 1) {
2946 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002947 float x, y;
2948 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002949 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2950 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002951 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952
2953 mPointerGesture.tapUpTime = when;
2954 getContext()->requestTimeoutAtTime(when +
2955 mConfig.pointerGestureTapDragInterval);
2956
2957 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002958 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002959 mPointerGesture.currentGestureIdBits.clear();
2960 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2961 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2962 mPointerGesture.currentGestureProperties[0].clear();
2963 mPointerGesture.currentGestureProperties[0].id =
2964 mPointerGesture.activeGestureId;
2965 mPointerGesture.currentGestureProperties[0].toolType =
2966 AMOTION_EVENT_TOOL_TYPE_FINGER;
2967 mPointerGesture.currentGestureCoords[0].clear();
2968 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2969 mPointerGesture.tapX);
2970 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2971 mPointerGesture.tapY);
2972 mPointerGesture.currentGestureCoords[0]
2973 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2974
2975 tapped = true;
2976 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002977 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2978 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979 }
2980 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002981 if (DEBUG_GESTURES) {
2982 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2983 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2984 (when - mPointerGesture.tapDownTime) * 0.000001f);
2985 } else {
2986 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2987 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 }
2990 }
2991
2992 mPointerVelocityControl.reset();
2993
2994 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002995 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002997 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002998 mPointerGesture.currentGestureIdBits.clear();
2999 }
3000 } else if (currentFingerCount == 1) {
3001 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3002 // The pointer follows the active touch point.
3003 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3004 // When in TAP_DRAG, emit MOVE events at the pointer location.
3005 ALOG_ASSERT(activeTouchId >= 0);
3006
Michael Wright227c5542020-07-02 18:30:52 +01003007 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3008 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003009 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003010 float x, y;
3011 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003012 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3013 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003014 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003015 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003016 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3017 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003018 }
3019 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003020 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3021 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003022 }
Michael Wright227c5542020-07-02 18:30:52 +01003023 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3024 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003025 }
3026
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003027 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003028 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003029 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003030 } else {
3031 mPointerVelocityControl.reset();
3032 }
3033
3034 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003035 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003036 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003037 down = true;
3038 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003039 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003040 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003041 *outFinishPreviousGesture = true;
3042 }
3043 mPointerGesture.activeGestureId = 0;
3044 down = false;
3045 }
3046
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003047 float x, y;
3048 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003049
3050 mPointerGesture.currentGestureIdBits.clear();
3051 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3052 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3053 mPointerGesture.currentGestureProperties[0].clear();
3054 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3055 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3056 mPointerGesture.currentGestureCoords[0].clear();
3057 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3058 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3059 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3060 down ? 1.0f : 0.0f);
3061
3062 if (lastFingerCount == 0 && currentFingerCount != 0) {
3063 mPointerGesture.resetTap();
3064 mPointerGesture.tapDownTime = when;
3065 mPointerGesture.tapX = x;
3066 mPointerGesture.tapY = y;
3067 }
3068 } else {
3069 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003070 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003071 }
3072
3073 mPointerController->setButtonState(mCurrentRawState.buttonState);
3074
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003075 if (DEBUG_GESTURES) {
3076 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3077 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3078 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3079 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3080 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3081 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3082 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3083 uint32_t id = idBits.clearFirstMarkedBit();
3084 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3085 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3086 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3087 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3088 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3089 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3090 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3091 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3092 }
3093 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3094 uint32_t id = idBits.clearFirstMarkedBit();
3095 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3096 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3097 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3098 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3099 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3100 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3101 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3102 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3103 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003104 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003105 return true;
3106}
3107
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003108bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3109 if (mPointerGesture.activeTouchId < 0) {
3110 mPointerGesture.resetQuietTime();
3111 return false;
3112 }
3113
3114 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3115 return true;
3116 }
3117
3118 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3119 bool isQuietTime = false;
3120 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3121 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3122 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3123 currentFingerCount < 2) {
3124 // Enter quiet time when exiting swipe or freeform state.
3125 // This is to prevent accidentally entering the hover state and flinging the
3126 // pointer when finishing a swipe and there is still one pointer left onscreen.
3127 isQuietTime = true;
3128 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3129 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3130 // Enter quiet time when releasing the button and there are still two or more
3131 // fingers down. This may indicate that one finger was used to press the button
3132 // but it has not gone up yet.
3133 isQuietTime = true;
3134 }
3135 if (isQuietTime) {
3136 mPointerGesture.quietTime = when;
3137 }
3138 return isQuietTime;
3139}
3140
3141std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3142 int32_t bestId = -1;
3143 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3144 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3145 uint32_t id = idBits.clearFirstMarkedBit();
3146 std::optional<float> vx =
3147 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3148 std::optional<float> vy =
3149 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3150 if (vx && vy) {
3151 float speed = hypotf(*vx, *vy);
3152 if (speed > bestSpeed) {
3153 bestId = id;
3154 bestSpeed = speed;
3155 }
3156 }
3157 }
3158 return std::make_pair(bestId, bestSpeed);
3159}
3160
3161void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3162 bool* finishPreviousGesture) {
3163 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3164 // to move before deciding what to do.
3165 //
3166 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3167 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3168 // just a press or long-press at the pointer location.
3169 //
3170 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3171 // pointer location.
3172 //
3173 // When the two fingers move enough or when additional fingers are added, we make a decision to
3174 // transition into SWIPE or FREEFORM mode accordingly.
3175 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3176 ALOG_ASSERT(activeTouchId >= 0);
3177
3178 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3179 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3180 bool settled =
3181 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3182 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3183 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3184 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3185 *finishPreviousGesture = true;
3186 } else if (!settled && currentFingerCount > lastFingerCount) {
3187 // Additional pointers have gone down but not yet settled.
3188 // Reset the gesture.
3189 ALOGD_IF(DEBUG_GESTURES,
3190 "Gestures: Resetting gesture since additional pointers went down for "
3191 "MULTITOUCH, settle time remaining %0.3fms",
3192 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3193 when) * 0.000001f);
3194 *cancelPreviousGesture = true;
3195 } else {
3196 // Continue previous gesture.
3197 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3198 }
3199
3200 if (*finishPreviousGesture || *cancelPreviousGesture) {
3201 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3202 mPointerGesture.activeGestureId = 0;
3203 mPointerGesture.referenceIdBits.clear();
3204 mPointerVelocityControl.reset();
3205
3206 // Use the centroid and pointer location as the reference points for the gesture.
3207 ALOGD_IF(DEBUG_GESTURES,
3208 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3209 "%0.3fms",
3210 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3211 when) * 0.000001f);
3212 mCurrentRawState.rawPointerData
3213 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3214 &mPointerGesture.referenceTouchY);
3215 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3216 &mPointerGesture.referenceGestureY);
3217 }
3218
3219 // Clear the reference deltas for fingers not yet included in the reference calculation.
3220 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3221 ~mPointerGesture.referenceIdBits.value);
3222 !idBits.isEmpty();) {
3223 uint32_t id = idBits.clearFirstMarkedBit();
3224 mPointerGesture.referenceDeltas[id].dx = 0;
3225 mPointerGesture.referenceDeltas[id].dy = 0;
3226 }
3227 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3228
3229 // Add delta for all fingers and calculate a common movement delta.
3230 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3231 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3232 mCurrentCookedState.fingerIdBits.value);
3233 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3234 bool first = (idBits == commonIdBits);
3235 uint32_t id = idBits.clearFirstMarkedBit();
3236 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3237 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3238 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3239 delta.dx += cpd.x - lpd.x;
3240 delta.dy += cpd.y - lpd.y;
3241
3242 if (first) {
3243 commonDeltaRawX = delta.dx;
3244 commonDeltaRawY = delta.dy;
3245 } else {
3246 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3247 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3248 }
3249 }
3250
3251 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3252 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3253 float dist[MAX_POINTER_ID + 1];
3254 int32_t distOverThreshold = 0;
3255 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3256 uint32_t id = idBits.clearFirstMarkedBit();
3257 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3258 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3259 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3260 distOverThreshold += 1;
3261 }
3262 }
3263
3264 // Only transition when at least two pointers have moved further than
3265 // the minimum distance threshold.
3266 if (distOverThreshold >= 2) {
3267 if (currentFingerCount > 2) {
3268 // There are more than two pointers, switch to FREEFORM.
3269 ALOGD_IF(DEBUG_GESTURES,
3270 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3271 currentFingerCount);
3272 *cancelPreviousGesture = true;
3273 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3274 } else {
3275 // There are exactly two pointers.
3276 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3277 uint32_t id1 = idBits.clearFirstMarkedBit();
3278 uint32_t id2 = idBits.firstMarkedBit();
3279 const RawPointerData::Pointer& p1 =
3280 mCurrentRawState.rawPointerData.pointerForId(id1);
3281 const RawPointerData::Pointer& p2 =
3282 mCurrentRawState.rawPointerData.pointerForId(id2);
3283 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3284 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3285 // There are two pointers but they are too far apart for a SWIPE,
3286 // switch to FREEFORM.
3287 ALOGD_IF(DEBUG_GESTURES,
3288 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3289 mutualDistance, mPointerGestureMaxSwipeWidth);
3290 *cancelPreviousGesture = true;
3291 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3292 } else {
3293 // There are two pointers. Wait for both pointers to start moving
3294 // before deciding whether this is a SWIPE or FREEFORM gesture.
3295 float dist1 = dist[id1];
3296 float dist2 = dist[id2];
3297 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3298 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3299 // Calculate the dot product of the displacement vectors.
3300 // When the vectors are oriented in approximately the same direction,
3301 // the angle betweeen them is near zero and the cosine of the angle
3302 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3303 // mag(v2).
3304 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3305 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3306 float dx1 = delta1.dx * mPointerXZoomScale;
3307 float dy1 = delta1.dy * mPointerYZoomScale;
3308 float dx2 = delta2.dx * mPointerXZoomScale;
3309 float dy2 = delta2.dy * mPointerYZoomScale;
3310 float dot = dx1 * dx2 + dy1 * dy2;
3311 float cosine = dot / (dist1 * dist2); // denominator always > 0
3312 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3313 // Pointers are moving in the same direction. Switch to SWIPE.
3314 ALOGD_IF(DEBUG_GESTURES,
3315 "Gestures: PRESS transitioned to SWIPE, "
3316 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3317 "cosine %0.3f >= %0.3f",
3318 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3319 mConfig.pointerGestureMultitouchMinDistance, cosine,
3320 mConfig.pointerGestureSwipeTransitionAngleCosine);
3321 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3322 } else {
3323 // Pointers are moving in different directions. Switch to FREEFORM.
3324 ALOGD_IF(DEBUG_GESTURES,
3325 "Gestures: PRESS transitioned to FREEFORM, "
3326 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3327 "cosine %0.3f < %0.3f",
3328 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3329 mConfig.pointerGestureMultitouchMinDistance, cosine,
3330 mConfig.pointerGestureSwipeTransitionAngleCosine);
3331 *cancelPreviousGesture = true;
3332 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3333 }
3334 }
3335 }
3336 }
3337 }
3338 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3339 // Switch from SWIPE to FREEFORM if additional pointers go down.
3340 // Cancel previous gesture.
3341 if (currentFingerCount > 2) {
3342 ALOGD_IF(DEBUG_GESTURES,
3343 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3344 currentFingerCount);
3345 *cancelPreviousGesture = true;
3346 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3347 }
3348 }
3349
3350 // Move the reference points based on the overall group motion of the fingers
3351 // except in PRESS mode while waiting for a transition to occur.
3352 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3353 (commonDeltaRawX || commonDeltaRawY)) {
3354 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3355 uint32_t id = idBits.clearFirstMarkedBit();
3356 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3357 delta.dx = 0;
3358 delta.dy = 0;
3359 }
3360
3361 mPointerGesture.referenceTouchX += commonDeltaRawX;
3362 mPointerGesture.referenceTouchY += commonDeltaRawY;
3363
3364 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3365 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3366
3367 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3368 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3369
3370 mPointerGesture.referenceGestureX += commonDeltaX;
3371 mPointerGesture.referenceGestureY += commonDeltaY;
3372 }
3373
3374 // Report gestures.
3375 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3376 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3377 // PRESS or SWIPE mode.
3378 ALOGD_IF(DEBUG_GESTURES,
3379 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3380 "currentTouchPointerCount=%d",
3381 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3382 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3383
3384 mPointerGesture.currentGestureIdBits.clear();
3385 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3386 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3387 mPointerGesture.currentGestureProperties[0].clear();
3388 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3389 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3390 mPointerGesture.currentGestureCoords[0].clear();
3391 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3392 mPointerGesture.referenceGestureX);
3393 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3394 mPointerGesture.referenceGestureY);
3395 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3396 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3397 float xOffset = static_cast<float>(commonDeltaRawX) /
3398 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3399 float yOffset = static_cast<float>(commonDeltaRawY) /
3400 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3401 mPointerGesture.currentGestureCoords[0]
3402 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3403 mPointerGesture.currentGestureCoords[0]
3404 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3405 }
3406 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3407 // FREEFORM mode.
3408 ALOGD_IF(DEBUG_GESTURES,
3409 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3410 "currentTouchPointerCount=%d",
3411 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3412 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3413
3414 mPointerGesture.currentGestureIdBits.clear();
3415
3416 BitSet32 mappedTouchIdBits;
3417 BitSet32 usedGestureIdBits;
3418 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3419 // Initially, assign the active gesture id to the active touch point
3420 // if there is one. No other touch id bits are mapped yet.
3421 if (!*cancelPreviousGesture) {
3422 mappedTouchIdBits.markBit(activeTouchId);
3423 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3424 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3425 mPointerGesture.activeGestureId;
3426 } else {
3427 mPointerGesture.activeGestureId = -1;
3428 }
3429 } else {
3430 // Otherwise, assume we mapped all touches from the previous frame.
3431 // Reuse all mappings that are still applicable.
3432 mappedTouchIdBits.value =
3433 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3434 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3435
3436 // Check whether we need to choose a new active gesture id because the
3437 // current went went up.
3438 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3439 ~mCurrentCookedState.fingerIdBits.value);
3440 !upTouchIdBits.isEmpty();) {
3441 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3442 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3443 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3444 mPointerGesture.activeGestureId = -1;
3445 break;
3446 }
3447 }
3448 }
3449
3450 ALOGD_IF(DEBUG_GESTURES,
3451 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3452 "activeGestureId=%d",
3453 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3454
3455 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3456 for (uint32_t i = 0; i < currentFingerCount; i++) {
3457 uint32_t touchId = idBits.clearFirstMarkedBit();
3458 uint32_t gestureId;
3459 if (!mappedTouchIdBits.hasBit(touchId)) {
3460 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3461 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3462 ALOGD_IF(DEBUG_GESTURES,
3463 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3464 gestureId);
3465 } else {
3466 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3467 ALOGD_IF(DEBUG_GESTURES,
3468 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3469 touchId, gestureId);
3470 }
3471 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3472 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3473
3474 const RawPointerData::Pointer& pointer =
3475 mCurrentRawState.rawPointerData.pointerForId(touchId);
3476 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3477 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3478 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3479
3480 mPointerGesture.currentGestureProperties[i].clear();
3481 mPointerGesture.currentGestureProperties[i].id = gestureId;
3482 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3483 mPointerGesture.currentGestureCoords[i].clear();
3484 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3485 mPointerGesture.referenceGestureX +
3486 deltaX);
3487 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3488 mPointerGesture.referenceGestureY +
3489 deltaY);
3490 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3491 }
3492
3493 if (mPointerGesture.activeGestureId < 0) {
3494 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3495 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3496 mPointerGesture.activeGestureId);
3497 }
3498 }
3499}
3500
Harry Cutts714d1ad2022-08-24 16:36:43 +00003501void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3502 const RawPointerData::Pointer& currentPointer =
3503 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3504 const RawPointerData::Pointer& lastPointer =
3505 mLastRawState.rawPointerData.pointerForId(pointerId);
3506 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3507 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3508
3509 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3510 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3511
3512 mPointerController->move(deltaX, deltaY);
3513}
3514
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003515std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3516 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517 mPointerSimple.currentCoords.clear();
3518 mPointerSimple.currentProperties.clear();
3519
3520 bool down, hovering;
3521 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3522 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3523 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003524 mPointerController
3525 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3526 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527
3528 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3529 down = !hovering;
3530
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003531 float x, y;
3532 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003533 mPointerSimple.currentCoords.copyFrom(
3534 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3535 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3536 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3537 mPointerSimple.currentProperties.id = 0;
3538 mPointerSimple.currentProperties.toolType =
3539 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3540 } else {
3541 down = false;
3542 hovering = false;
3543 }
3544
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003545 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546}
3547
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003548std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3549 uint32_t policyFlags) {
3550 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003551}
3552
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003553std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3554 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003555 mPointerSimple.currentCoords.clear();
3556 mPointerSimple.currentProperties.clear();
3557
3558 bool down, hovering;
3559 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3560 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003561 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003562 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 } else {
3564 mPointerVelocityControl.reset();
3565 }
3566
3567 down = isPointerDown(mCurrentRawState.buttonState);
3568 hovering = !down;
3569
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003570 float x, y;
3571 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003572 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573 mPointerSimple.currentCoords.copyFrom(
3574 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3575 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3576 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3577 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3578 hovering ? 0.0f : 1.0f);
3579 mPointerSimple.currentProperties.id = 0;
3580 mPointerSimple.currentProperties.toolType =
3581 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3582 } else {
3583 mPointerVelocityControl.reset();
3584
3585 down = false;
3586 hovering = false;
3587 }
3588
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003589 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590}
3591
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003592std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3593 uint32_t policyFlags) {
3594 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003595
3596 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003597
3598 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003599}
3600
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003601std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3602 uint32_t policyFlags, bool down,
3603 bool hovering) {
3604 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003605 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606
3607 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003608 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003609 mPointerController->clearSpots();
3610 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003611 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003612 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003613 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003614 }
Garfield Tan9514d782020-11-10 16:37:23 -08003615 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003616
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003617 float xCursorPosition, yCursorPosition;
3618 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003619
3620 if (mPointerSimple.down && !down) {
3621 mPointerSimple.down = false;
3622
3623 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003624 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3625 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3626 0, metaState, mLastRawState.buttonState,
3627 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3628 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3629 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3630 yCursorPosition, mPointerSimple.downTime,
3631 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003632 }
3633
3634 if (mPointerSimple.hovering && !hovering) {
3635 mPointerSimple.hovering = false;
3636
3637 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003638 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3639 mSource, displayId, policyFlags,
3640 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3641 mLastRawState.buttonState, MotionClassification::NONE,
3642 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3643 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3644 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3645 yCursorPosition, mPointerSimple.downTime,
3646 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003647 }
3648
3649 if (down) {
3650 if (!mPointerSimple.down) {
3651 mPointerSimple.down = true;
3652 mPointerSimple.downTime = when;
3653
3654 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003655 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3656 mSource, displayId, policyFlags,
3657 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3658 mCurrentRawState.buttonState, MotionClassification::NONE,
3659 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3660 &mPointerSimple.currentProperties,
3661 &mPointerSimple.currentCoords, mOrientedXPrecision,
3662 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3663 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003664 }
3665
3666 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003667 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3668 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3669 0, 0, metaState, mCurrentRawState.buttonState,
3670 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3671 &mPointerSimple.currentProperties,
3672 &mPointerSimple.currentCoords, mOrientedXPrecision,
3673 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3674 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003675 }
3676
3677 if (hovering) {
3678 if (!mPointerSimple.hovering) {
3679 mPointerSimple.hovering = true;
3680
3681 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003682 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3683 mSource, displayId, policyFlags,
3684 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3685 mCurrentRawState.buttonState, MotionClassification::NONE,
3686 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3687 &mPointerSimple.currentProperties,
3688 &mPointerSimple.currentCoords, mOrientedXPrecision,
3689 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3690 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003691 }
3692
3693 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003694 out.push_back(
3695 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3696 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3697 metaState, mCurrentRawState.buttonState,
3698 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3699 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3700 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3701 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003702 }
3703
3704 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3705 float vscroll = mCurrentRawState.rawVScroll;
3706 float hscroll = mCurrentRawState.rawHScroll;
3707 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3708 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3709
3710 // Send scroll.
3711 PointerCoords pointerCoords;
3712 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3713 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3714 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3715
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003716 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3717 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3718 0, 0, metaState, mCurrentRawState.buttonState,
3719 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3720 &mPointerSimple.currentProperties, &pointerCoords,
3721 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3722 yCursorPosition, mPointerSimple.downTime,
3723 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003724 }
3725
3726 // Save state.
3727 if (down || hovering) {
3728 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3729 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3730 } else {
3731 mPointerSimple.reset();
3732 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003733 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003734}
3735
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003736std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3737 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003738 mPointerSimple.currentCoords.clear();
3739 mPointerSimple.currentProperties.clear();
3740
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003741 return dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003742}
3743
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003744NotifyMotionArgs TouchInputMapper::dispatchMotion(
3745 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3746 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
3747 int32_t edgeFlags, const PointerProperties* properties, const PointerCoords* coords,
3748 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
3749 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003750 PointerCoords pointerCoords[MAX_POINTERS];
3751 PointerProperties pointerProperties[MAX_POINTERS];
3752 uint32_t pointerCount = 0;
3753 while (!idBits.isEmpty()) {
3754 uint32_t id = idBits.clearFirstMarkedBit();
3755 uint32_t index = idToIndex[id];
3756 pointerProperties[pointerCount].copyFrom(properties[index]);
3757 pointerCoords[pointerCount].copyFrom(coords[index]);
3758
3759 if (changedId >= 0 && id == uint32_t(changedId)) {
3760 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3761 }
3762
3763 pointerCount += 1;
3764 }
3765
3766 ALOG_ASSERT(pointerCount != 0);
3767
3768 if (changedId >= 0 && pointerCount == 1) {
3769 // Replace initial down and final up action.
3770 // We can compare the action without masking off the changed pointer index
3771 // because we know the index is 0.
3772 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3773 action = AMOTION_EVENT_ACTION_DOWN;
3774 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003775 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3776 action = AMOTION_EVENT_ACTION_CANCEL;
3777 } else {
3778 action = AMOTION_EVENT_ACTION_UP;
3779 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003780 } else {
3781 // Can't happen.
3782 ALOG_ASSERT(false);
3783 }
3784 }
3785 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3786 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003787 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003788 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003789 }
3790 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3791 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003792 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003793 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003794 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003795 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3796 policyFlags, action, actionButton, flags, metaState, buttonState,
3797 classification, edgeFlags, pointerCount, pointerProperties,
3798 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3799 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003800}
3801
3802bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3803 const PointerCoords* inCoords,
3804 const uint32_t* inIdToIndex,
3805 PointerProperties* outProperties,
3806 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3807 BitSet32 idBits) const {
3808 bool changed = false;
3809 while (!idBits.isEmpty()) {
3810 uint32_t id = idBits.clearFirstMarkedBit();
3811 uint32_t inIndex = inIdToIndex[id];
3812 uint32_t outIndex = outIdToIndex[id];
3813
3814 const PointerProperties& curInProperties = inProperties[inIndex];
3815 const PointerCoords& curInCoords = inCoords[inIndex];
3816 PointerProperties& curOutProperties = outProperties[outIndex];
3817 PointerCoords& curOutCoords = outCoords[outIndex];
3818
3819 if (curInProperties != curOutProperties) {
3820 curOutProperties.copyFrom(curInProperties);
3821 changed = true;
3822 }
3823
3824 if (curInCoords != curOutCoords) {
3825 curOutCoords.copyFrom(curInCoords);
3826 changed = true;
3827 }
3828 }
3829 return changed;
3830}
3831
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003832std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3833 std::list<NotifyArgs> out;
3834 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3835 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3836 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003837}
3838
Prabir Pradhan1728b212021-10-19 16:00:03 -07003839// Transform input device coordinates to display panel coordinates.
3840void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003841 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3842 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3843
arthurhunga36b28e2020-12-29 20:28:15 +08003844 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3845 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3846
Prabir Pradhan1728b212021-10-19 16:00:03 -07003847 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003848 // 0 - no swap and reverse.
3849 // 90 - swap x/y and reverse y.
3850 // 180 - reverse x, y.
3851 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003852 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003853 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003854 x = xScaled;
3855 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003856 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003857 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003858 y = xScaledMax;
3859 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003860 break;
3861 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003862 x = xScaledMax;
3863 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003864 break;
3865 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003866 y = xScaled;
3867 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003868 break;
3869 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003870 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003871 }
3872}
3873
Prabir Pradhan1728b212021-10-19 16:00:03 -07003874bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003875 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3876 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3877
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003878 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003879 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003880 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003881 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003882}
3883
3884const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3885 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003886 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3887 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3888 "left=%d, top=%d, right=%d, bottom=%d",
3889 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3890 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003891
3892 if (virtualKey.isHit(x, y)) {
3893 return &virtualKey;
3894 }
3895 }
3896
3897 return nullptr;
3898}
3899
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003900void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3901 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3902 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003903
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003904 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003905
3906 if (currentPointerCount == 0) {
3907 // No pointers to assign.
3908 return;
3909 }
3910
3911 if (lastPointerCount == 0) {
3912 // All pointers are new.
3913 for (uint32_t i = 0; i < currentPointerCount; i++) {
3914 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003915 current.rawPointerData.pointers[i].id = id;
3916 current.rawPointerData.idToIndex[id] = i;
3917 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003918 }
3919 return;
3920 }
3921
3922 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003923 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003924 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003925 uint32_t id = last.rawPointerData.pointers[0].id;
3926 current.rawPointerData.pointers[0].id = id;
3927 current.rawPointerData.idToIndex[id] = 0;
3928 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003929 return;
3930 }
3931
3932 // General case.
3933 // We build a heap of squared euclidean distances between current and last pointers
3934 // associated with the current and last pointer indices. Then, we find the best
3935 // match (by distance) for each current pointer.
3936 // The pointers must have the same tool type but it is possible for them to
3937 // transition from hovering to touching or vice-versa while retaining the same id.
3938 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3939
3940 uint32_t heapSize = 0;
3941 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3942 currentPointerIndex++) {
3943 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3944 lastPointerIndex++) {
3945 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003946 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003947 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003948 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003949 if (currentPointer.toolType == lastPointer.toolType) {
3950 int64_t deltaX = currentPointer.x - lastPointer.x;
3951 int64_t deltaY = currentPointer.y - lastPointer.y;
3952
3953 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3954
3955 // Insert new element into the heap (sift up).
3956 heap[heapSize].currentPointerIndex = currentPointerIndex;
3957 heap[heapSize].lastPointerIndex = lastPointerIndex;
3958 heap[heapSize].distance = distance;
3959 heapSize += 1;
3960 }
3961 }
3962 }
3963
3964 // Heapify
3965 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3966 startIndex -= 1;
3967 for (uint32_t parentIndex = startIndex;;) {
3968 uint32_t childIndex = parentIndex * 2 + 1;
3969 if (childIndex >= heapSize) {
3970 break;
3971 }
3972
3973 if (childIndex + 1 < heapSize &&
3974 heap[childIndex + 1].distance < heap[childIndex].distance) {
3975 childIndex += 1;
3976 }
3977
3978 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3979 break;
3980 }
3981
3982 swap(heap[parentIndex], heap[childIndex]);
3983 parentIndex = childIndex;
3984 }
3985 }
3986
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003987 if (DEBUG_POINTER_ASSIGNMENT) {
3988 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3989 for (size_t i = 0; i < heapSize; i++) {
3990 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3991 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3992 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003993 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003994
3995 // Pull matches out by increasing order of distance.
3996 // To avoid reassigning pointers that have already been matched, the loop keeps track
3997 // of which last and current pointers have been matched using the matchedXXXBits variables.
3998 // It also tracks the used pointer id bits.
3999 BitSet32 matchedLastBits(0);
4000 BitSet32 matchedCurrentBits(0);
4001 BitSet32 usedIdBits(0);
4002 bool first = true;
4003 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
4004 while (heapSize > 0) {
4005 if (first) {
4006 // The first time through the loop, we just consume the root element of
4007 // the heap (the one with smallest distance).
4008 first = false;
4009 } else {
4010 // Previous iterations consumed the root element of the heap.
4011 // Pop root element off of the heap (sift down).
4012 heap[0] = heap[heapSize];
4013 for (uint32_t parentIndex = 0;;) {
4014 uint32_t childIndex = parentIndex * 2 + 1;
4015 if (childIndex >= heapSize) {
4016 break;
4017 }
4018
4019 if (childIndex + 1 < heapSize &&
4020 heap[childIndex + 1].distance < heap[childIndex].distance) {
4021 childIndex += 1;
4022 }
4023
4024 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4025 break;
4026 }
4027
4028 swap(heap[parentIndex], heap[childIndex]);
4029 parentIndex = childIndex;
4030 }
4031
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004032 if (DEBUG_POINTER_ASSIGNMENT) {
4033 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4034 for (size_t j = 0; j < heapSize; j++) {
4035 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4036 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4037 heap[j].distance);
4038 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004039 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004040 }
4041
4042 heapSize -= 1;
4043
4044 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4045 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4046
4047 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4048 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4049
4050 matchedCurrentBits.markBit(currentPointerIndex);
4051 matchedLastBits.markBit(lastPointerIndex);
4052
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004053 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4054 current.rawPointerData.pointers[currentPointerIndex].id = id;
4055 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4056 current.rawPointerData.markIdBit(id,
4057 current.rawPointerData.isHovering(
4058 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004059 usedIdBits.markBit(id);
4060
Harry Cutts45483602022-08-24 14:36:48 +00004061 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4062 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4063 ", distance=%" PRIu64,
4064 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004065 break;
4066 }
4067 }
4068
4069 // Assign fresh ids to pointers that were not matched in the process.
4070 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4071 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4072 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4073
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004074 current.rawPointerData.pointers[currentPointerIndex].id = id;
4075 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4076 current.rawPointerData.markIdBit(id,
4077 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004078
Harry Cutts45483602022-08-24 14:36:48 +00004079 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4080 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4081 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004082 }
4083}
4084
4085int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4086 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4087 return AKEY_STATE_VIRTUAL;
4088 }
4089
4090 for (const VirtualKey& virtualKey : mVirtualKeys) {
4091 if (virtualKey.keyCode == keyCode) {
4092 return AKEY_STATE_UP;
4093 }
4094 }
4095
4096 return AKEY_STATE_UNKNOWN;
4097}
4098
4099int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4100 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4101 return AKEY_STATE_VIRTUAL;
4102 }
4103
4104 for (const VirtualKey& virtualKey : mVirtualKeys) {
4105 if (virtualKey.scanCode == scanCode) {
4106 return AKEY_STATE_UP;
4107 }
4108 }
4109
4110 return AKEY_STATE_UNKNOWN;
4111}
4112
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004113bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4114 const std::vector<int32_t>& keyCodes,
4115 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004116 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004117 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004118 if (virtualKey.keyCode == keyCodes[i]) {
4119 outFlags[i] = 1;
4120 }
4121 }
4122 }
4123
4124 return true;
4125}
4126
4127std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4128 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004129 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004130 return std::make_optional(mPointerController->getDisplayId());
4131 } else {
4132 return std::make_optional(mViewport.displayId);
4133 }
4134 }
4135 return std::nullopt;
4136}
4137
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004138} // namespace android