blob: da58efde31fad633c450e4561d240c72177e52b4 [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
Michael Wright227c5542020-07-02 18:30:52 +0100192 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700193 info->addMotionRange(mOrientedRanges.x);
194 info->addMotionRange(mOrientedRanges.y);
195 info->addMotionRange(mOrientedRanges.pressure);
196
Chris Yef74dc422020-09-02 22:41:50 -0700197 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700198 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
199 //
200 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
201 // motion, i.e. the hardware dimensions, as the finger could move completely across the
202 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700203 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
204 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
205 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
206 x.fuzz, x.resolution);
207 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
208 y.fuzz, y.resolution);
209 }
210
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700211 if (mOrientedRanges.size) {
212 info->addMotionRange(*mOrientedRanges.size);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700213 }
214
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700215 if (mOrientedRanges.touchMajor) {
216 info->addMotionRange(*mOrientedRanges.touchMajor);
217 info->addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700218 }
219
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700220 if (mOrientedRanges.toolMajor) {
221 info->addMotionRange(*mOrientedRanges.toolMajor);
222 info->addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700223 }
224
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700225 if (mOrientedRanges.orientation) {
226 info->addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700227 }
228
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700229 if (mOrientedRanges.distance) {
230 info->addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700231 }
232
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700233 if (mOrientedRanges.tilt) {
234 info->addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700235 }
236
237 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
238 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
239 0.0f);
240 }
241 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
242 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
243 0.0f);
244 }
Michael Wright227c5542020-07-02 18:30:52 +0100245 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700246 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
247 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
248 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
249 x.fuzz, x.resolution);
250 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
251 y.fuzz, y.resolution);
252 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
253 x.fuzz, x.resolution);
254 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
255 y.fuzz, y.resolution);
256 }
257 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
258 }
259}
260
261void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700262 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800263 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700264 dumpParameters(dump);
265 dumpVirtualKeys(dump);
266 dumpRawPointerAxes(dump);
267 dumpCalibration(dump);
268 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700269 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700270
271 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700272 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
273 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
274 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
275 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
276 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
277 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
278 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
279 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
280 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
281 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
282 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
283 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
284 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
285 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
286
287 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
288 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
289 mLastRawState.rawPointerData.pointerCount);
290 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
291 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
292 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
293 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
294 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
295 "toolType=%d, isHovering=%s\n",
296 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
297 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
298 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
299 pointer.distance, pointer.toolType, toString(pointer.isHovering));
300 }
301
302 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
303 mLastCookedState.buttonState);
304 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
305 mLastCookedState.cookedPointerData.pointerCount);
306 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
307 const PointerProperties& pointerProperties =
308 mLastCookedState.cookedPointerData.pointerProperties[i];
309 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000310 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
311 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
312 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700313 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
314 "toolType=%d, isHovering=%s\n",
315 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000316 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
326 pointerProperties.toolType,
327 toString(mLastCookedState.cookedPointerData.isHovering(i)));
328 }
329
330 dump += INDENT3 "Stylus Fusion:\n";
331 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
332 toString(mExternalStylusConnected));
333 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
334 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
335 mExternalStylusFusionTimeout);
336 dump += INDENT3 "External Stylus State:\n";
337 dumpStylusState(dump, mExternalStylusState);
338
Michael Wright227c5542020-07-02 18:30:52 +0100339 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700340 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
341 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
342 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
343 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
344 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
345 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
346 }
347}
348
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700349std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
350 const InputReaderConfiguration* config,
351 uint32_t changes) {
352 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700353
354 mConfig = *config;
355
356 if (!changes) { // first time only
357 // Configure basic parameters.
358 configureParameters();
359
360 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mCursorScrollAccumulator.configure(getDeviceContext());
362 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700363
364 // Configure absolute axis information.
365 configureRawPointerAxes();
366
367 // Prepare input device calibration.
368 parseCalibration();
369 resolveCalibration();
370 }
371
372 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
373 // Update location calibration to reflect current settings
374 updateAffineTransformation();
375 }
376
377 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
378 // Update pointer speed.
379 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
380 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
381 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 }
383
384 bool resetNeeded = false;
385 if (!changes ||
386 (changes &
387 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800388 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
390 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
391 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700392 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700393 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700394 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700395 }
396
397 if (changes && resetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000398 // If the device needs to be reset, cancel any ongoing gestures and reset the state.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700399 out += cancelTouch(when, when);
400 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000401
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 // Send reset, unless this is the first time the device has been configured,
403 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700404 out.push_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700405 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700406 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700407}
408
409void TouchInputMapper::resolveExternalStylusPresence() {
410 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800411 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700412 mExternalStylusConnected = !devices.empty();
413
414 if (!mExternalStylusConnected) {
415 resetExternalStylus();
416 }
417}
418
419void TouchInputMapper::configureParameters() {
420 // Use the pointer presentation mode for devices that do not support distinct
421 // multitouch. The spot-based presentation relies on being able to accurately
422 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800423 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100424 ? Parameters::GestureMode::SINGLE_TOUCH
425 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700427 std::string gestureModeString;
428 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800429 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700430 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100431 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700432 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100433 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700434 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700435 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436 }
437 }
438
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800439 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700440 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100441 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800442 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100444 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700445 } else {
446 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100447 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448 }
449
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800450 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700451
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700452 std::string deviceTypeString;
453 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100456 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100458 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100460 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700461 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700462 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463 }
464 }
465
Michael Wright227c5542020-07-02 18:30:52 +0100466 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700467 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800468 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700469
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700470 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700471 std::string orientationString;
472 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700473 orientationString)) {
474 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
475 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
476 } else if (orientationString == "ORIENTATION_90") {
477 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
478 } else if (orientationString == "ORIENTATION_180") {
479 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
480 } else if (orientationString == "ORIENTATION_270") {
481 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
482 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700483 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700484 }
485 }
486
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700487 mParameters.hasAssociatedDisplay = false;
488 mParameters.associatedDisplayIsExternal = false;
489 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100490 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
491 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700492 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100493 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700495 std::string uniqueDisplayId;
496 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800497 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700498 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
499 }
500 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800501 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502 mParameters.hasAssociatedDisplay = true;
503 }
504
505 // Initial downs on external touch devices should wake the device.
506 // Normally we don't do this for internal touch screens to prevent them from waking
507 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800508 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700509 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700510}
511
512void TouchInputMapper::dumpParameters(std::string& dump) {
513 dump += INDENT3 "Parameters:\n";
514
Dominik Laskowski75788452021-02-09 18:51:25 -0800515 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700516
Dominik Laskowski75788452021-02-09 18:51:25 -0800517 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700518
519 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
520 "displayId='%s'\n",
521 toString(mParameters.hasAssociatedDisplay),
522 toString(mParameters.associatedDisplayIsExternal),
523 mParameters.uniqueDisplayId.c_str());
524 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800525 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700526}
527
528void TouchInputMapper::configureRawPointerAxes() {
529 mRawPointerAxes.clear();
530}
531
532void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
533 dump += INDENT3 "Raw Touch Axes:\n";
534 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
535 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
536 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
537 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
538 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
547}
548
549bool TouchInputMapper::hasExternalStylus() const {
550 return mExternalStylusConnected;
551}
552
553/**
554 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000555 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800556 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000557 * 3. Get the matching viewport by either unique id in idc file or by the display type
558 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800559 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700560 */
561std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800562 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000563 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800564 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700565 }
566
Christine Franks2a2293c2022-01-18 11:51:16 -0800567 const std::optional<std::string> associatedDisplayUniqueId =
568 getDeviceContext().getAssociatedDisplayUniqueId();
569 if (associatedDisplayUniqueId) {
570 return getDeviceContext().getAssociatedViewport();
571 }
572
Michael Wright227c5542020-07-02 18:30:52 +0100573 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800574 std::optional<DisplayViewport> viewport =
575 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
576 if (viewport) {
577 return viewport;
578 } else {
579 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
580 mConfig.defaultPointerDisplayId);
581 }
582 }
583
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700584 // Check if uniqueDisplayId is specified in idc file.
585 if (!mParameters.uniqueDisplayId.empty()) {
586 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
587 }
588
589 ViewportType viewportTypeToUse;
590 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100591 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700592 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100593 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700594 }
595
596 std::optional<DisplayViewport> viewport =
597 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100598 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700599 ALOGW("Input device %s should be associated with external display, "
600 "fallback to internal one for the external viewport is not found.",
601 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100602 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700603 }
604
605 return viewport;
606 }
607
608 // No associated display, return a non-display viewport.
609 DisplayViewport newViewport;
610 // Raw width and height in the natural orientation.
611 int32_t rawWidth = mRawPointerAxes.getRawWidth();
612 int32_t rawHeight = mRawPointerAxes.getRawHeight();
613 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
614 return std::make_optional(newViewport);
615}
616
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800617int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
618 if (resolution < 0) {
619 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
620 getDeviceName().c_str());
621 return 0;
622 }
623 return resolution;
624}
625
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800626void TouchInputMapper::initializeSizeRanges() {
627 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
628 mSizeScale = 0.0f;
629 return;
630 }
631
632 // Size of diagonal axis.
633 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
634
635 // Size factors.
636 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
637 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
638 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
639 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
640 } else {
641 mSizeScale = 0.0f;
642 }
643
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700644 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
645 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
646 .source = mSource,
647 .min = 0,
648 .max = diagonalSize,
649 .flat = 0,
650 .fuzz = 0,
651 .resolution = 0,
652 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800653
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800654 if (mRawPointerAxes.touchMajor.valid) {
655 mRawPointerAxes.touchMajor.resolution =
656 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700657 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800658 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800659
660 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700661 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800662 if (mRawPointerAxes.touchMinor.valid) {
663 mRawPointerAxes.touchMinor.resolution =
664 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700665 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800666 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800667
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700668 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
669 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
670 .source = mSource,
671 .min = 0,
672 .max = diagonalSize,
673 .flat = 0,
674 .fuzz = 0,
675 .resolution = 0,
676 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800677 if (mRawPointerAxes.toolMajor.valid) {
678 mRawPointerAxes.toolMajor.resolution =
679 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700680 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800681 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800682
683 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700684 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800685 if (mRawPointerAxes.toolMinor.valid) {
686 mRawPointerAxes.toolMinor.resolution =
687 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700688 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800689 }
690
691 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700692 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
693 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
694 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
695 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800696 } else {
697 // Support for other calibrations can be added here.
698 ALOGW("%s calibration is not supported for size ranges at the moment. "
699 "Using raw resolution instead",
700 ftl::enum_string(mCalibration.sizeCalibration).c_str());
701 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800702
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700703 mOrientedRanges.size = InputDeviceInfo::MotionRange{
704 .axis = AMOTION_EVENT_AXIS_SIZE,
705 .source = mSource,
706 .min = 0,
707 .max = 1.0,
708 .flat = 0,
709 .fuzz = 0,
710 .resolution = 0,
711 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800712}
713
714void TouchInputMapper::initializeOrientedRanges() {
715 // Configure X and Y factors.
716 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
717 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
718 mXPrecision = 1.0f / mXScale;
719 mYPrecision = 1.0f / mYScale;
720
721 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
722 mOrientedRanges.x.source = mSource;
723 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
724 mOrientedRanges.y.source = mSource;
725
726 // Scale factor for terms that are not oriented in a particular axis.
727 // If the pixels are square then xScale == yScale otherwise we fake it
728 // by choosing an average.
729 mGeometricScale = avg(mXScale, mYScale);
730
731 initializeSizeRanges();
732
733 // Pressure factors.
734 mPressureScale = 0;
735 float pressureMax = 1.0;
736 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
737 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700738 if (mCalibration.pressureScale) {
739 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800740 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
741 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
742 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
743 }
744 }
745
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700746 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
747 .axis = AMOTION_EVENT_AXIS_PRESSURE,
748 .source = mSource,
749 .min = 0,
750 .max = pressureMax,
751 .flat = 0,
752 .fuzz = 0,
753 .resolution = 0,
754 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800755
756 // Tilt
757 mTiltXCenter = 0;
758 mTiltXScale = 0;
759 mTiltYCenter = 0;
760 mTiltYScale = 0;
761 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
762 if (mHaveTilt) {
763 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
764 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
765 mTiltXScale = M_PI / 180;
766 mTiltYScale = M_PI / 180;
767
768 if (mRawPointerAxes.tiltX.resolution) {
769 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
770 }
771 if (mRawPointerAxes.tiltY.resolution) {
772 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
773 }
774
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700775 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
776 .axis = AMOTION_EVENT_AXIS_TILT,
777 .source = mSource,
778 .min = 0,
779 .max = M_PI_2,
780 .flat = 0,
781 .fuzz = 0,
782 .resolution = 0,
783 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800784 }
785
786 // Orientation
787 mOrientationScale = 0;
788 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700789 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
790 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
791 .source = mSource,
792 .min = -M_PI,
793 .max = M_PI,
794 .flat = 0,
795 .fuzz = 0,
796 .resolution = 0,
797 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800798
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800799 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
800 if (mCalibration.orientationCalibration ==
801 Calibration::OrientationCalibration::INTERPOLATED) {
802 if (mRawPointerAxes.orientation.valid) {
803 if (mRawPointerAxes.orientation.maxValue > 0) {
804 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
805 } else if (mRawPointerAxes.orientation.minValue < 0) {
806 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
807 } else {
808 mOrientationScale = 0;
809 }
810 }
811 }
812
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700813 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
814 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
815 .source = mSource,
816 .min = -M_PI_2,
817 .max = M_PI_2,
818 .flat = 0,
819 .fuzz = 0,
820 .resolution = 0,
821 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800822 }
823
824 // Distance
825 mDistanceScale = 0;
826 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
827 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700828 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800829 }
830
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700831 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800832
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700833 .axis = AMOTION_EVENT_AXIS_DISTANCE,
834 .source = mSource,
835 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
836 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
837 .flat = 0,
838 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
839 .resolution = 0,
840 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800841 }
842
843 // Compute oriented precision, scales and ranges.
844 // Note that the maximum value reported is an inclusive maximum value so it is one
845 // unit less than the total width or height of the display.
846 switch (mInputDeviceOrientation) {
847 case DISPLAY_ORIENTATION_90:
848 case DISPLAY_ORIENTATION_270:
849 mOrientedXPrecision = mYPrecision;
850 mOrientedYPrecision = mXPrecision;
851
852 mOrientedRanges.x.min = 0;
853 mOrientedRanges.x.max = mDisplayHeight - 1;
854 mOrientedRanges.x.flat = 0;
855 mOrientedRanges.x.fuzz = 0;
856 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
857
858 mOrientedRanges.y.min = 0;
859 mOrientedRanges.y.max = mDisplayWidth - 1;
860 mOrientedRanges.y.flat = 0;
861 mOrientedRanges.y.fuzz = 0;
862 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
863 break;
864
865 default:
866 mOrientedXPrecision = mXPrecision;
867 mOrientedYPrecision = mYPrecision;
868
869 mOrientedRanges.x.min = 0;
870 mOrientedRanges.x.max = mDisplayWidth - 1;
871 mOrientedRanges.x.flat = 0;
872 mOrientedRanges.x.fuzz = 0;
873 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
874
875 mOrientedRanges.y.min = 0;
876 mOrientedRanges.y.max = mDisplayHeight - 1;
877 mOrientedRanges.y.flat = 0;
878 mOrientedRanges.y.fuzz = 0;
879 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
880 break;
881 }
882}
883
Prabir Pradhan1728b212021-10-19 16:00:03 -0700884void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000885 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700886
887 resolveExternalStylusPresence();
888
889 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100890 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000891 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700892 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100893 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700894 if (hasStylus()) {
895 mSource |= AINPUT_SOURCE_STYLUS;
896 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800897 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700898 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100899 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700900 if (hasStylus()) {
901 mSource |= AINPUT_SOURCE_STYLUS;
902 }
903 if (hasExternalStylus()) {
904 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
905 }
Michael Wright227c5542020-07-02 18:30:52 +0100906 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700907 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100908 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700909 } else {
910 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100911 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700912 }
913
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000914 const std::optional<DisplayViewport> newViewportOpt = findViewport();
915
916 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700917 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
918 ALOGW("Touch device '%s' did not report support for X or Y axis! "
919 "The device will be inoperable.",
920 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100921 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000922 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700923 ALOGI("Touch device '%s' could not query the properties of its associated "
924 "display. The device will be inoperable until the display size "
925 "becomes available.",
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->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000929 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
930 getDeviceName().c_str(), getDeviceId());
931 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000932 }
933
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700934 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700935 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
936 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000937 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
938 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
939 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
940 const float rawMeanResolution =
941 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700942
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000943 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
944 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700945 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700946 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000947 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
948 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
949 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700950
Michael Wright227c5542020-07-02 18:30:52 +0100951 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700952 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700953 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
954 int32_t naturalPhysicalLeft, naturalPhysicalTop;
955 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700956
Prabir Pradhan1728b212021-10-19 16:00:03 -0700957 // Apply the inverse of the input device orientation so that the input device is
958 // configured in the same orientation as the viewport. The input device orientation will
959 // be re-applied by mInputDeviceOrientation.
960 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700961 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700962 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700963 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700964 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
965 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800966 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700967 naturalPhysicalTop = mViewport.physicalLeft;
968 naturalDeviceWidth = mViewport.deviceHeight;
969 naturalDeviceHeight = mViewport.deviceWidth;
970 break;
971 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700972 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
973 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
974 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
975 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
976 naturalDeviceWidth = mViewport.deviceWidth;
977 naturalDeviceHeight = mViewport.deviceHeight;
978 break;
979 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700980 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
981 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
982 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800983 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700984 naturalDeviceWidth = mViewport.deviceHeight;
985 naturalDeviceHeight = mViewport.deviceWidth;
986 break;
987 case DISPLAY_ORIENTATION_0:
988 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700989 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
990 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
991 naturalPhysicalLeft = mViewport.physicalLeft;
992 naturalPhysicalTop = mViewport.physicalTop;
993 naturalDeviceWidth = mViewport.deviceWidth;
994 naturalDeviceHeight = mViewport.deviceHeight;
995 break;
996 }
997
998 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
999 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
1000 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
1001 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
1002 }
1003
1004 mPhysicalWidth = naturalPhysicalWidth;
1005 mPhysicalHeight = naturalPhysicalHeight;
1006 mPhysicalLeft = naturalPhysicalLeft;
1007 mPhysicalTop = naturalPhysicalTop;
1008
Prabir Pradhan1728b212021-10-19 16:00:03 -07001009 const int32_t oldDisplayWidth = mDisplayWidth;
1010 const int32_t oldDisplayHeight = mDisplayHeight;
1011 mDisplayWidth = naturalDeviceWidth;
1012 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -07001013
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001014 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1015 // anything if the device is already orientation-aware. If the device is not
1016 // orientation-aware, then we need to apply the inverse rotation of the display so that
1017 // when the display rotation is applied later as a part of the per-window transform, we
1018 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001019 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001020 ? DISPLAY_ORIENTATION_0
1021 : getInverseRotation(mViewport.orientation);
1022 // For orientation-aware devices that work in the un-rotated coordinate space, the
1023 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001024 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
1025 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
1026 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001027
1028 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001029 mInputDeviceOrientation =
1030 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001031 } else {
1032 mPhysicalWidth = rawWidth;
1033 mPhysicalHeight = rawHeight;
1034 mPhysicalLeft = 0;
1035 mPhysicalTop = 0;
1036
Prabir Pradhan1728b212021-10-19 16:00:03 -07001037 mDisplayWidth = rawWidth;
1038 mDisplayHeight = rawHeight;
1039 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001040 }
1041 }
1042
1043 // If moving between pointer modes, need to reset some state.
1044 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1045 if (deviceModeChanged) {
1046 mOrientedRanges.clear();
1047 }
1048
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001049 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
1050 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +01001051 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001052 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001053 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1054 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001055 if (mPointerController == nullptr) {
1056 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001058 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001059 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1060 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001061 } else {
lilinnandef700b2022-06-17 19:32:01 +08001062 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1063 !mConfig.showTouches) {
1064 mPointerController->clearSpots();
1065 }
Michael Wright17db18e2020-06-26 20:51:44 +01001066 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067 }
1068
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001069 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001070 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1071 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001072 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1073 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001074
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001075 configureVirtualKeys();
1076
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001077 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001078
1079 // Location
1080 updateAffineTransformation();
1081
Michael Wright227c5542020-07-02 18:30:52 +01001082 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001083 // Compute pointer gesture detection parameters.
1084 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001085 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086
1087 // Scale movements such that one whole swipe of the touch pad covers a
1088 // given area relative to the diagonal size of the display when no acceleration
1089 // is applied.
1090 // Assume that the touch pad has a square aspect ratio such that movements in
1091 // X and Y of the same number of raw units cover the same physical distance.
1092 mPointerXMovementScale =
1093 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1094 mPointerYMovementScale = mPointerXMovementScale;
1095
1096 // Scale zooms to cover a smaller range of the display than movements do.
1097 // This value determines the area around the pointer that is affected by freeform
1098 // pointer gestures.
1099 mPointerXZoomScale =
1100 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1101 mPointerYZoomScale = mPointerXZoomScale;
1102
HQ Liue6983c72022-04-19 22:14:56 +00001103 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1104 // axis is non positive value.
1105 const float minFreeformGestureWidth =
1106 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1107
1108 mPointerGestureMaxSwipeWidth =
1109 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1110 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111 }
1112
1113 // Inform the dispatcher about the changes.
1114 *outResetNeeded = true;
1115 bumpGeneration();
1116 }
1117}
1118
Prabir Pradhan1728b212021-10-19 16:00:03 -07001119void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001120 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001121 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1122 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1124 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1125 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1126 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001127 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128}
1129
1130void TouchInputMapper::configureVirtualKeys() {
1131 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001132 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133
1134 mVirtualKeys.clear();
1135
1136 if (virtualKeyDefinitions.size() == 0) {
1137 return;
1138 }
1139
1140 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1141 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1142 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1143 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1144
1145 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1146 VirtualKey virtualKey;
1147
1148 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1149 int32_t keyCode;
1150 int32_t dummyKeyMetaState;
1151 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001152 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1153 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1155 continue; // drop the key
1156 }
1157
1158 virtualKey.keyCode = keyCode;
1159 virtualKey.flags = flags;
1160
1161 // convert the key definition's display coordinates into touch coordinates for a hit box
1162 int32_t halfWidth = virtualKeyDefinition.width / 2;
1163 int32_t halfHeight = virtualKeyDefinition.height / 2;
1164
1165 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001166 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 touchScreenLeft;
1168 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001169 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001171 virtualKey.hitTop =
1172 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001173 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001174 virtualKey.hitBottom =
1175 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 touchScreenTop;
1177 mVirtualKeys.push_back(virtualKey);
1178 }
1179}
1180
1181void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1182 if (!mVirtualKeys.empty()) {
1183 dump += INDENT3 "Virtual Keys:\n";
1184
1185 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1186 const VirtualKey& virtualKey = mVirtualKeys[i];
1187 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1188 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1189 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1190 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1191 }
1192 }
1193}
1194
1195void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001196 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 Calibration& out = mCalibration;
1198
1199 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001201 std::string sizeCalibrationString;
1202 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001214 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 }
1216 }
1217
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001218 float sizeScale;
1219
1220 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1221 out.sizeScale = sizeScale;
1222 }
1223 float sizeBias;
1224 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1225 out.sizeBias = sizeBias;
1226 }
1227 bool sizeIsSummed;
1228 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1229 out.sizeIsSummed = sizeIsSummed;
1230 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231
1232 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001233 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001234 std::string pressureCalibrationString;
1235 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001237 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001239 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001241 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 } else if (pressureCalibrationString != "default") {
1243 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001244 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 }
1246 }
1247
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001248 float pressureScale;
1249 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1250 out.pressureScale = pressureScale;
1251 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252
1253 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001254 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001255 std::string orientationCalibrationString;
1256 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001258 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001260 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001262 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 } else if (orientationCalibrationString != "default") {
1264 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001265 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267 }
1268
1269 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001270 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001271 std::string distanceCalibrationString;
1272 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001274 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001276 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 } else if (distanceCalibrationString != "default") {
1278 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001279 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 }
1281 }
1282
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001283 float distanceScale;
1284 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1285 out.distanceScale = distanceScale;
1286 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287
Michael Wright227c5542020-07-02 18:30:52 +01001288 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001289 std::string coverageCalibrationString;
1290 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001292 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001294 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 } else if (coverageCalibrationString != "default") {
1296 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001297 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 }
1299 }
1300}
1301
1302void TouchInputMapper::resolveCalibration() {
1303 // Size
1304 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001305 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1306 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 }
1308 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001309 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 }
1311
1312 // Pressure
1313 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001314 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1315 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 }
1317 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001318 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 }
1320
1321 // Orientation
1322 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001323 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1324 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 }
1326 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001327 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 }
1329
1330 // Distance
1331 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001332 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1333 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 }
1335 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001336 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 }
1338
1339 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001340 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1341 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001342 }
1343}
1344
1345void TouchInputMapper::dumpCalibration(std::string& dump) {
1346 dump += INDENT3 "Calibration:\n";
1347
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001348 dump += INDENT4 "touch.size.calibration: ";
1349 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001351 if (mCalibration.sizeScale) {
1352 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 }
1354
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001355 if (mCalibration.sizeBias) {
1356 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 }
1358
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001359 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001361 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001362 }
1363
1364 // Pressure
1365 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001366 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001367 dump += INDENT4 "touch.pressure.calibration: none\n";
1368 break;
Michael Wright227c5542020-07-02 18:30:52 +01001369 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001370 dump += INDENT4 "touch.pressure.calibration: physical\n";
1371 break;
Michael Wright227c5542020-07-02 18:30:52 +01001372 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001373 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1374 break;
1375 default:
1376 ALOG_ASSERT(false);
1377 }
1378
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001379 if (mCalibration.pressureScale) {
1380 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001381 }
1382
1383 // Orientation
1384 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001385 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386 dump += INDENT4 "touch.orientation.calibration: none\n";
1387 break;
Michael Wright227c5542020-07-02 18:30:52 +01001388 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001389 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1390 break;
Michael Wright227c5542020-07-02 18:30:52 +01001391 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001392 dump += INDENT4 "touch.orientation.calibration: vector\n";
1393 break;
1394 default:
1395 ALOG_ASSERT(false);
1396 }
1397
1398 // Distance
1399 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001400 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001401 dump += INDENT4 "touch.distance.calibration: none\n";
1402 break;
Michael Wright227c5542020-07-02 18:30:52 +01001403 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001404 dump += INDENT4 "touch.distance.calibration: scaled\n";
1405 break;
1406 default:
1407 ALOG_ASSERT(false);
1408 }
1409
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001410 if (mCalibration.distanceScale) {
1411 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001412 }
1413
1414 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001415 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001416 dump += INDENT4 "touch.coverage.calibration: none\n";
1417 break;
Michael Wright227c5542020-07-02 18:30:52 +01001418 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001419 dump += INDENT4 "touch.coverage.calibration: box\n";
1420 break;
1421 default:
1422 ALOG_ASSERT(false);
1423 }
1424}
1425
1426void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1427 dump += INDENT3 "Affine Transformation:\n";
1428
1429 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1430 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1431 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1432 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1433 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1434 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1435}
1436
1437void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001438 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001439 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440}
1441
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001442std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001443 mCursorButtonAccumulator.reset(getDeviceContext());
1444 mCursorScrollAccumulator.reset(getDeviceContext());
1445 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446
1447 mPointerVelocityControl.reset();
1448 mWheelXVelocityControl.reset();
1449 mWheelYVelocityControl.reset();
1450
1451 mRawStatesPending.clear();
1452 mCurrentRawState.clear();
1453 mCurrentCookedState.clear();
1454 mLastRawState.clear();
1455 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001456 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001457 mSentHoverEnter = false;
1458 mHavePointerIds = false;
1459 mCurrentMotionAborted = false;
1460 mDownTime = 0;
1461
1462 mCurrentVirtualKey.down = false;
1463
1464 mPointerGesture.reset();
1465 mPointerSimple.reset();
1466 resetExternalStylus();
1467
1468 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001469 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001470 mPointerController->clearSpots();
1471 }
1472
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001473 return InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001474}
1475
1476void TouchInputMapper::resetExternalStylus() {
1477 mExternalStylusState.clear();
1478 mExternalStylusId = -1;
1479 mExternalStylusFusionTimeout = LLONG_MAX;
1480 mExternalStylusDataPending = false;
1481}
1482
1483void TouchInputMapper::clearStylusDataPendingFlags() {
1484 mExternalStylusDataPending = false;
1485 mExternalStylusFusionTimeout = LLONG_MAX;
1486}
1487
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001488std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001489 mCursorButtonAccumulator.process(rawEvent);
1490 mCursorScrollAccumulator.process(rawEvent);
1491 mTouchButtonAccumulator.process(rawEvent);
1492
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001493 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001494 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001495 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001497 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498}
1499
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001500std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1501 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001502 if (mDeviceMode == DeviceMode::DISABLED) {
1503 // Only save the last pending state when the device is disabled.
1504 mRawStatesPending.clear();
1505 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001506 // Push a new state.
1507 mRawStatesPending.emplace_back();
1508
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001509 RawState& next = mRawStatesPending.back();
1510 next.clear();
1511 next.when = when;
1512 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001513
1514 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001515 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001516 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1517
1518 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001519 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1520 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521 mCursorScrollAccumulator.finishSync();
1522
1523 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001524 syncTouch(when, &next);
1525
1526 // The last RawState is the actually second to last, since we just added a new state
1527 const RawState& last =
1528 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001529
1530 // Assign pointer ids.
1531 if (!mHavePointerIds) {
1532 assignPointerIds(last, next);
1533 }
1534
Harry Cutts45483602022-08-24 14:36:48 +00001535 ALOGD_IF(DEBUG_RAW_EVENTS,
1536 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1537 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1538 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1539 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1540 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1541 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001542
Arthur Hung9ad18942021-06-19 02:04:46 +00001543 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1544 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1545 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1546 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1547 next.rawPointerData.hoveringIdBits.value);
1548 }
1549
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001550 out += processRawTouches(false /*timeout*/);
1551 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001552}
1553
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001554std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1555 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001556 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001557 // Drop all input if the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001558 out += cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001559 mCurrentCookedState.clear();
1560 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001561 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001562 }
1563
1564 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1565 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1566 // touching the current state will only observe the events that have been dispatched to the
1567 // rest of the pipeline.
1568 const size_t N = mRawStatesPending.size();
1569 size_t count;
1570 for (count = 0; count < N; count++) {
1571 const RawState& next = mRawStatesPending[count];
1572
1573 // A failure to assign the stylus id means that we're waiting on stylus data
1574 // and so should defer the rest of the pipeline.
1575 if (assignExternalStylusId(next, timeout)) {
1576 break;
1577 }
1578
1579 // All ready to go.
1580 clearStylusDataPendingFlags();
1581 mCurrentRawState.copyFrom(next);
1582 if (mCurrentRawState.when < mLastRawState.when) {
1583 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001584 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001585 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001586 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001587 }
1588 if (count != 0) {
1589 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1590 }
1591
1592 if (mExternalStylusDataPending) {
1593 if (timeout) {
1594 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1595 clearStylusDataPendingFlags();
1596 mCurrentRawState.copyFrom(mLastRawState);
Harry Cutts45483602022-08-24 14:36:48 +00001597 ALOGD_IF(DEBUG_STYLUS_FUSION,
1598 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001599 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001600 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001601 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1602 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1603 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1604 }
1605 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001606 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001607}
1608
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001609std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1610 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001611 // Always start with a clean state.
1612 mCurrentCookedState.clear();
1613
1614 // Apply stylus buttons to current raw state.
1615 applyExternalStylusButtonState(when);
1616
1617 // Handle policy on initial down or hover events.
1618 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1619 mCurrentRawState.rawPointerData.pointerCount != 0;
1620
1621 uint32_t policyFlags = 0;
1622 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1623 if (initialDown || buttonsPressed) {
1624 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001625 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626 getContext()->fadePointer();
1627 }
1628
1629 if (mParameters.wake) {
1630 policyFlags |= POLICY_FLAG_WAKE;
1631 }
1632 }
1633
1634 // Consume raw off-screen touches before cooking pointer data.
1635 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001636 bool consumed;
1637 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1638 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001639 mCurrentRawState.rawPointerData.clear();
1640 }
1641
1642 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1643 // with cooked pointer data that has the same ids and indices as the raw data.
1644 // The following code can use either the raw or cooked data, as needed.
1645 cookPointerData();
1646
1647 // Apply stylus pressure to current cooked state.
1648 applyExternalStylusTouchState(when);
1649
1650 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001651 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1652 mSource, mViewport.displayId, policyFlags,
1653 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001654
1655 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001656 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001657 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1658 uint32_t id = idBits.clearFirstMarkedBit();
1659 const RawPointerData::Pointer& pointer =
1660 mCurrentRawState.rawPointerData.pointerForId(id);
1661 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1662 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1663 mCurrentCookedState.stylusIdBits.markBit(id);
1664 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1665 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1666 mCurrentCookedState.fingerIdBits.markBit(id);
1667 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1668 mCurrentCookedState.mouseIdBits.markBit(id);
1669 }
1670 }
1671 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1672 uint32_t id = idBits.clearFirstMarkedBit();
1673 const RawPointerData::Pointer& pointer =
1674 mCurrentRawState.rawPointerData.pointerForId(id);
1675 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1676 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1677 mCurrentCookedState.stylusIdBits.markBit(id);
1678 }
1679 }
1680
1681 // Stylus takes precedence over all tools, then mouse, then finger.
1682 PointerUsage pointerUsage = mPointerUsage;
1683 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1684 mCurrentCookedState.mouseIdBits.clear();
1685 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001686 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001687 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1688 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001689 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001690 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1691 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001692 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001693 }
1694
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001695 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001696 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001697 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001698 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001699 out += dispatchButtonRelease(when, readTime, policyFlags);
1700 out += dispatchHoverExit(when, readTime, policyFlags);
1701 out += dispatchTouches(when, readTime, policyFlags);
1702 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1703 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001704 }
1705
1706 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1707 mCurrentMotionAborted = false;
1708 }
1709 }
1710
1711 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001712 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1713 mSource, mViewport.displayId, policyFlags,
1714 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001715
1716 // Clear some transient state.
1717 mCurrentRawState.rawVScroll = 0;
1718 mCurrentRawState.rawHScroll = 0;
1719
1720 // Copy current touch to last touch in preparation for the next cycle.
1721 mLastRawState.copyFrom(mCurrentRawState);
1722 mLastCookedState.copyFrom(mCurrentCookedState);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001723 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001724}
1725
Garfield Tanc734e4f2021-01-15 20:01:39 -08001726void TouchInputMapper::updateTouchSpots() {
1727 if (!mConfig.showTouches || mPointerController == nullptr) {
1728 return;
1729 }
1730
1731 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1732 // clear touch spots.
1733 if (mDeviceMode != DeviceMode::DIRECT &&
1734 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1735 return;
1736 }
1737
1738 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1739 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1740
1741 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001742 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1743 mCurrentCookedState.cookedPointerData.idToIndex,
1744 mCurrentCookedState.cookedPointerData.touchingIdBits,
1745 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001746}
1747
1748bool TouchInputMapper::isTouchScreen() {
1749 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1750 mParameters.hasAssociatedDisplay;
1751}
1752
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001753void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001754 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001755 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1756 }
1757}
1758
1759void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1760 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1761 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1762
1763 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1764 float pressure = mExternalStylusState.pressure;
1765 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1766 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1767 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1768 }
1769 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1770 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1771
1772 PointerProperties& properties =
1773 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1774 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1775 properties.toolType = mExternalStylusState.toolType;
1776 }
1777 }
1778}
1779
1780bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001781 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001782 return false;
1783 }
1784
1785 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1786 state.rawPointerData.pointerCount != 0;
1787 if (initialDown) {
1788 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001789 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001790 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1791 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001792 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793 resetExternalStylus();
1794 } else {
1795 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1796 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1797 }
Harry Cutts45483602022-08-24 14:36:48 +00001798 ALOGD_IF(DEBUG_STYLUS_FUSION,
1799 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1800 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001801 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1802 return true;
1803 }
1804 }
1805
1806 // Check if the stylus pointer has gone up.
1807 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001808 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001809 mExternalStylusId = -1;
1810 }
1811
1812 return false;
1813}
1814
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001815std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1816 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001817 if (mDeviceMode == DeviceMode::POINTER) {
1818 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001819 // Since this is a synthetic event, we can consider its latency to be zero
1820 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001821 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001822 }
Michael Wright227c5542020-07-02 18:30:52 +01001823 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001824 if (mExternalStylusFusionTimeout < when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001825 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001826 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1827 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1828 }
1829 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001830 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001831}
1832
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001833std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1834 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001835 mExternalStylusState.copyFrom(state);
1836 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1837 // We're either in the middle of a fused stream of data or we're waiting on data before
1838 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1839 // data.
1840 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001841 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001842 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001843 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001844}
1845
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001846std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1847 uint32_t policyFlags, bool& outConsumed) {
1848 outConsumed = false;
1849 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001850 // Check for release of a virtual key.
1851 if (mCurrentVirtualKey.down) {
1852 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1853 // Pointer went up while virtual key was down.
1854 mCurrentVirtualKey.down = false;
1855 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001856 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1857 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1858 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001859 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1860 AKEY_EVENT_FLAG_FROM_SYSTEM |
1861 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001862 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001863 outConsumed = true;
1864 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001865 }
1866
1867 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1868 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1869 const RawPointerData::Pointer& pointer =
1870 mCurrentRawState.rawPointerData.pointerForId(id);
1871 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1872 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1873 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001874 outConsumed = true;
1875 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001876 }
1877 }
1878
1879 // Pointer left virtual key area or another pointer also went down.
1880 // Send key cancellation but do not consume the touch yet.
1881 // This is useful when the user swipes through from the virtual key area
1882 // into the main display surface.
1883 mCurrentVirtualKey.down = false;
1884 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001885 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1886 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001887 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1888 AKEY_EVENT_FLAG_FROM_SYSTEM |
1889 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1890 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001891 }
1892 }
1893
1894 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1895 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1896 // Pointer just went down. Check for virtual key press or off-screen touches.
1897 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1898 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001899 // Skip checking whether the pointer is inside the physical frame if the device is in
1900 // unscaled mode.
1901 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1902 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001903 // If exactly one pointer went down, check for virtual key hit.
1904 // Otherwise we will drop the entire stroke.
1905 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1906 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1907 if (virtualKey) {
1908 mCurrentVirtualKey.down = true;
1909 mCurrentVirtualKey.downTime = when;
1910 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1911 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1912 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001913 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1914 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001915
1916 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001917 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1918 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1919 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1921 AKEY_EVENT_ACTION_DOWN,
1922 AKEY_EVENT_FLAG_FROM_SYSTEM |
1923 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924 }
1925 }
1926 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001927 outConsumed = true;
1928 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001929 }
1930 }
1931
1932 // Disable all virtual key touches that happen within a short time interval of the
1933 // most recent touch within the screen area. The idea is to filter out stray
1934 // virtual key presses when interacting with the touch screen.
1935 //
1936 // Problems we're trying to solve:
1937 //
1938 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1939 // virtual key area that is implemented by a separate touch panel and accidentally
1940 // triggers a virtual key.
1941 //
1942 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1943 // area and accidentally triggers a virtual key. This often happens when virtual keys
1944 // are layed out below the screen near to where the on screen keyboard's space bar
1945 // is displayed.
1946 if (mConfig.virtualKeyQuietTime > 0 &&
1947 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001948 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001949 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001950 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001951}
1952
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001953NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1954 uint32_t policyFlags, int32_t keyEventAction,
1955 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001956 int32_t keyCode = mCurrentVirtualKey.keyCode;
1957 int32_t scanCode = mCurrentVirtualKey.scanCode;
1958 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001959 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001960 policyFlags |= POLICY_FLAG_VIRTUAL;
1961
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001962 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1963 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1964 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001965}
1966
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001967std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1968 uint32_t policyFlags) {
1969 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001970 if (mCurrentMotionAborted) {
1971 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001972 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001973 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001974 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1975 if (!currentIdBits.isEmpty()) {
1976 int32_t metaState = getContext()->getGlobalMetaState();
1977 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001978 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
1979 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
1980 AMOTION_EVENT_EDGE_FLAG_NONE,
1981 mCurrentCookedState.cookedPointerData.pointerProperties,
1982 mCurrentCookedState.cookedPointerData.pointerCoords,
1983 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1984 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1985 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001986 mCurrentMotionAborted = true;
1987 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001988 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001989}
1990
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001991std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1992 uint32_t policyFlags) {
1993 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001994 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1995 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1996 int32_t metaState = getContext()->getGlobalMetaState();
1997 int32_t buttonState = mCurrentCookedState.buttonState;
1998
1999 if (currentIdBits == lastIdBits) {
2000 if (!currentIdBits.isEmpty()) {
2001 // No pointer id changes so this is a move event.
2002 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002003 out.push_back(
2004 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2005 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2006 mCurrentCookedState.cookedPointerData.pointerProperties,
2007 mCurrentCookedState.cookedPointerData.pointerCoords,
2008 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2009 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2010 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002011 }
2012 } else {
2013 // There may be pointers going up and pointers going down and pointers moving
2014 // all at the same time.
2015 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2016 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2017 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2018 BitSet32 dispatchedIdBits(lastIdBits.value);
2019
2020 // Update last coordinates of pointers that have moved so that we observe the new
2021 // pointer positions at the same time as other pointers that have just gone up.
2022 bool moveNeeded =
2023 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2024 mCurrentCookedState.cookedPointerData.pointerCoords,
2025 mCurrentCookedState.cookedPointerData.idToIndex,
2026 mLastCookedState.cookedPointerData.pointerProperties,
2027 mLastCookedState.cookedPointerData.pointerCoords,
2028 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2029 if (buttonState != mLastCookedState.buttonState) {
2030 moveNeeded = true;
2031 }
2032
2033 // Dispatch pointer up events.
2034 while (!upIdBits.isEmpty()) {
2035 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002036 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002037 if (isCanceled) {
2038 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2039 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002040 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2041 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2042 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2043 buttonState, 0,
2044 mLastCookedState.cookedPointerData.pointerProperties,
2045 mLastCookedState.cookedPointerData.pointerCoords,
2046 mLastCookedState.cookedPointerData.idToIndex,
2047 dispatchedIdBits, upId, mOrientedXPrecision,
2048 mOrientedYPrecision, mDownTime,
2049 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002050 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002051 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002052 }
2053
2054 // Dispatch move events if any of the remaining pointers moved from their old locations.
2055 // Although applications receive new locations as part of individual pointer up
2056 // events, they do not generally handle them except when presented in a move event.
2057 if (moveNeeded && !moveIdBits.isEmpty()) {
2058 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002059 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2060 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2061 mCurrentCookedState.cookedPointerData.pointerProperties,
2062 mCurrentCookedState.cookedPointerData.pointerCoords,
2063 mCurrentCookedState.cookedPointerData.idToIndex,
2064 dispatchedIdBits, -1, mOrientedXPrecision,
2065 mOrientedYPrecision, mDownTime,
2066 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002067 }
2068
2069 // Dispatch pointer down events using the new pointer locations.
2070 while (!downIdBits.isEmpty()) {
2071 uint32_t downId = downIdBits.clearFirstMarkedBit();
2072 dispatchedIdBits.markBit(downId);
2073
2074 if (dispatchedIdBits.count() == 1) {
2075 // First pointer is going down. Set down time.
2076 mDownTime = when;
2077 }
2078
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002079 out.push_back(
2080 dispatchMotion(when, readTime, policyFlags, mSource,
2081 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2082 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2083 mCurrentCookedState.cookedPointerData.pointerCoords,
2084 mCurrentCookedState.cookedPointerData.idToIndex,
2085 dispatchedIdBits, downId, mOrientedXPrecision,
2086 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002087 }
2088 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002089 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002090}
2091
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002092std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2093 uint32_t policyFlags) {
2094 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002095 if (mSentHoverEnter &&
2096 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2097 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2098 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002099 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2100 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2101 mLastCookedState.buttonState, 0,
2102 mLastCookedState.cookedPointerData.pointerProperties,
2103 mLastCookedState.cookedPointerData.pointerCoords,
2104 mLastCookedState.cookedPointerData.idToIndex,
2105 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2106 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2107 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002108 mSentHoverEnter = false;
2109 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002110 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111}
2112
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002113std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2114 uint32_t policyFlags) {
2115 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002116 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2117 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2118 int32_t metaState = getContext()->getGlobalMetaState();
2119 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002120 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2121 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2122 mCurrentRawState.buttonState, 0,
2123 mCurrentCookedState.cookedPointerData.pointerProperties,
2124 mCurrentCookedState.cookedPointerData.pointerCoords,
2125 mCurrentCookedState.cookedPointerData.idToIndex,
2126 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2127 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2128 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002129 mSentHoverEnter = true;
2130 }
2131
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002132 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2133 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2134 mCurrentRawState.buttonState, 0,
2135 mCurrentCookedState.cookedPointerData.pointerProperties,
2136 mCurrentCookedState.cookedPointerData.pointerCoords,
2137 mCurrentCookedState.cookedPointerData.idToIndex,
2138 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2139 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2140 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002142 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002143}
2144
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002145std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2146 uint32_t policyFlags) {
2147 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002148 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2149 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2150 const int32_t metaState = getContext()->getGlobalMetaState();
2151 int32_t buttonState = mLastCookedState.buttonState;
2152 while (!releasedButtons.isEmpty()) {
2153 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2154 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002155 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2156 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2157 metaState, buttonState, 0,
2158 mCurrentCookedState.cookedPointerData.pointerProperties,
2159 mCurrentCookedState.cookedPointerData.pointerCoords,
2160 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2161 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2162 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002164 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165}
2166
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002167std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2168 uint32_t policyFlags) {
2169 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2171 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2172 const int32_t metaState = getContext()->getGlobalMetaState();
2173 int32_t buttonState = mLastCookedState.buttonState;
2174 while (!pressedButtons.isEmpty()) {
2175 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2176 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002177 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2178 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2179 buttonState, 0,
2180 mCurrentCookedState.cookedPointerData.pointerProperties,
2181 mCurrentCookedState.cookedPointerData.pointerCoords,
2182 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2183 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2184 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002186 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002187}
2188
2189const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2190 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2191 return cookedPointerData.touchingIdBits;
2192 }
2193 return cookedPointerData.hoveringIdBits;
2194}
2195
2196void TouchInputMapper::cookPointerData() {
2197 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2198
2199 mCurrentCookedState.cookedPointerData.clear();
2200 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2201 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2202 mCurrentRawState.rawPointerData.hoveringIdBits;
2203 mCurrentCookedState.cookedPointerData.touchingIdBits =
2204 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002205 mCurrentCookedState.cookedPointerData.canceledIdBits =
2206 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002207
2208 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2209 mCurrentCookedState.buttonState = 0;
2210 } else {
2211 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2212 }
2213
2214 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002215 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002216 for (uint32_t i = 0; i < currentPointerCount; i++) {
2217 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2218
2219 // Size
2220 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2221 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002222 case Calibration::SizeCalibration::GEOMETRIC:
2223 case Calibration::SizeCalibration::DIAMETER:
2224 case Calibration::SizeCalibration::BOX:
2225 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002226 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2227 touchMajor = in.touchMajor;
2228 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2229 toolMajor = in.toolMajor;
2230 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2231 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2232 : in.touchMajor;
2233 } else if (mRawPointerAxes.touchMajor.valid) {
2234 toolMajor = touchMajor = in.touchMajor;
2235 toolMinor = touchMinor =
2236 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2237 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2238 : in.touchMajor;
2239 } else if (mRawPointerAxes.toolMajor.valid) {
2240 touchMajor = toolMajor = in.toolMajor;
2241 touchMinor = toolMinor =
2242 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2243 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2244 : in.toolMajor;
2245 } else {
2246 ALOG_ASSERT(false,
2247 "No touch or tool axes. "
2248 "Size calibration should have been resolved to NONE.");
2249 touchMajor = 0;
2250 touchMinor = 0;
2251 toolMajor = 0;
2252 toolMinor = 0;
2253 size = 0;
2254 }
2255
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002256 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002257 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2258 if (touchingCount > 1) {
2259 touchMajor /= touchingCount;
2260 touchMinor /= touchingCount;
2261 toolMajor /= touchingCount;
2262 toolMinor /= touchingCount;
2263 size /= touchingCount;
2264 }
2265 }
2266
Michael Wright227c5542020-07-02 18:30:52 +01002267 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002268 touchMajor *= mGeometricScale;
2269 touchMinor *= mGeometricScale;
2270 toolMajor *= mGeometricScale;
2271 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002272 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002273 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2274 touchMinor = touchMajor;
2275 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2276 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002277 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002278 touchMinor = touchMajor;
2279 toolMinor = toolMajor;
2280 }
2281
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002282 mCalibration.applySizeScaleAndBias(touchMajor);
2283 mCalibration.applySizeScaleAndBias(touchMinor);
2284 mCalibration.applySizeScaleAndBias(toolMajor);
2285 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002286 size *= mSizeScale;
2287 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002288 case Calibration::SizeCalibration::DEFAULT:
2289 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2290 break;
2291 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 touchMajor = 0;
2293 touchMinor = 0;
2294 toolMajor = 0;
2295 toolMinor = 0;
2296 size = 0;
2297 break;
2298 }
2299
2300 // Pressure
2301 float pressure;
2302 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002303 case Calibration::PressureCalibration::PHYSICAL:
2304 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002305 pressure = in.pressure * mPressureScale;
2306 break;
2307 default:
2308 pressure = in.isHovering ? 0 : 1;
2309 break;
2310 }
2311
2312 // Tilt and Orientation
2313 float tilt;
2314 float orientation;
2315 if (mHaveTilt) {
2316 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2317 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2318 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2319 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2320 } else {
2321 tilt = 0;
2322
2323 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002324 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002325 orientation = in.orientation * mOrientationScale;
2326 break;
Michael Wright227c5542020-07-02 18:30:52 +01002327 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002328 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2329 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2330 if (c1 != 0 || c2 != 0) {
2331 orientation = atan2f(c1, c2) * 0.5f;
2332 float confidence = hypotf(c1, c2);
2333 float scale = 1.0f + confidence / 16.0f;
2334 touchMajor *= scale;
2335 touchMinor /= scale;
2336 toolMajor *= scale;
2337 toolMinor /= scale;
2338 } else {
2339 orientation = 0;
2340 }
2341 break;
2342 }
2343 default:
2344 orientation = 0;
2345 }
2346 }
2347
2348 // Distance
2349 float distance;
2350 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002351 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 distance = in.distance * mDistanceScale;
2353 break;
2354 default:
2355 distance = 0;
2356 }
2357
2358 // Coverage
2359 int32_t rawLeft, rawTop, rawRight, rawBottom;
2360 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002361 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2363 rawRight = in.toolMinor & 0x0000ffff;
2364 rawBottom = in.toolMajor & 0x0000ffff;
2365 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2366 break;
2367 default:
2368 rawLeft = rawTop = rawRight = rawBottom = 0;
2369 break;
2370 }
2371
2372 // Adjust X,Y coords for device calibration
2373 // TODO: Adjust coverage coords?
2374 float xTransformed = in.x, yTransformed = in.y;
2375 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002376 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377
Prabir Pradhan1728b212021-10-19 16:00:03 -07002378 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 float left, top, right, bottom;
2380
Prabir Pradhan1728b212021-10-19 16:00:03 -07002381 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002383 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2384 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2385 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2386 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002388 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002390 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 }
2392 break;
2393 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2395 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002396 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2397 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002399 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002401 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 }
2403 break;
2404 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2406 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002407 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2408 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002410 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002412 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002413 }
2414 break;
2415 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002416 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2417 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2418 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2419 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 break;
2421 }
2422
2423 // Write output coords.
2424 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2425 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002426 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2427 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002428 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2429 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2430 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2431 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2432 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2433 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2434 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002435 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2437 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2438 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2439 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2440 } else {
2441 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2442 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2443 }
2444
Chris Ye364fdb52020-08-05 15:07:56 -07002445 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002446 uint32_t id = in.id;
2447 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2448 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2449 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2450 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2451 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2452 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2453 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2454 }
2455
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 // Write output properties.
2457 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 properties.clear();
2459 properties.id = id;
2460 properties.toolType = in.toolType;
2461
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002462 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002464 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 }
2466}
2467
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002468std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2469 uint32_t policyFlags,
2470 PointerUsage pointerUsage) {
2471 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 mPointerUsage = pointerUsage;
2475 }
2476
2477 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002478 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002479 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 break;
Michael Wright227c5542020-07-02 18:30:52 +01002481 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002482 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483 break;
Michael Wright227c5542020-07-02 18:30:52 +01002484 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002485 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 break;
Michael Wright227c5542020-07-02 18:30:52 +01002487 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002488 break;
2489 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002490 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491}
2492
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002493std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2494 uint32_t policyFlags) {
2495 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002497 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002498 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002499 break;
Michael Wright227c5542020-07-02 18:30:52 +01002500 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002501 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 break;
Michael Wright227c5542020-07-02 18:30:52 +01002503 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002504 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002505 break;
Michael Wright227c5542020-07-02 18:30:52 +01002506 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002507 break;
2508 }
2509
Michael Wright227c5542020-07-02 18:30:52 +01002510 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002511 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512}
2513
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002514std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2515 uint32_t policyFlags,
2516 bool isTimeout) {
2517 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002518 // Update current gesture coordinates.
2519 bool cancelPreviousGesture, finishPreviousGesture;
2520 bool sendEvents =
2521 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2522 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002523 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 }
2525 if (finishPreviousGesture) {
2526 cancelPreviousGesture = false;
2527 }
2528
2529 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002530 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002531 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002532 if (finishPreviousGesture || cancelPreviousGesture) {
2533 mPointerController->clearSpots();
2534 }
2535
Michael Wright227c5542020-07-02 18:30:52 +01002536 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002537 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2538 mPointerGesture.currentGestureIdToIndex,
2539 mPointerGesture.currentGestureIdBits,
2540 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541 }
2542 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002543 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 }
2545
2546 // Show or hide the pointer if needed.
2547 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002548 case PointerGesture::Mode::NEUTRAL:
2549 case PointerGesture::Mode::QUIET:
2550 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2551 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002553 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002554 }
2555 break;
Michael Wright227c5542020-07-02 18:30:52 +01002556 case PointerGesture::Mode::TAP:
2557 case PointerGesture::Mode::TAP_DRAG:
2558 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2559 case PointerGesture::Mode::HOVER:
2560 case PointerGesture::Mode::PRESS:
2561 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002562 // Unfade the pointer when the current gesture manipulates the
2563 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002564 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002565 break;
Michael Wright227c5542020-07-02 18:30:52 +01002566 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002567 // Fade the pointer when the current gesture manipulates a different
2568 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002569 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002570 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002571 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002572 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002573 }
2574 break;
2575 }
2576
2577 // Send events!
2578 int32_t metaState = getContext()->getGlobalMetaState();
2579 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002580 const MotionClassification classification =
2581 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2582 ? MotionClassification::TWO_FINGER_SWIPE
2583 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002584
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002585 uint32_t flags = 0;
2586
2587 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2588 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2589 }
2590
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591 // Update last coordinates of pointers that have moved so that we observe the new
2592 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002593 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2594 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2595 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2596 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2597 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2598 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002599 bool moveNeeded = false;
2600 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2601 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2602 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2603 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2604 mPointerGesture.lastGestureIdBits.value);
2605 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2606 mPointerGesture.currentGestureCoords,
2607 mPointerGesture.currentGestureIdToIndex,
2608 mPointerGesture.lastGestureProperties,
2609 mPointerGesture.lastGestureCoords,
2610 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2611 if (buttonState != mLastCookedState.buttonState) {
2612 moveNeeded = true;
2613 }
2614 }
2615
2616 // Send motion events for all pointers that went up or were canceled.
2617 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2618 if (!dispatchedGestureIdBits.isEmpty()) {
2619 if (cancelPreviousGesture) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002620 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2621 AMOTION_EVENT_ACTION_CANCEL, 0, flags, metaState,
2622 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2623 mPointerGesture.lastGestureProperties,
2624 mPointerGesture.lastGestureCoords,
2625 mPointerGesture.lastGestureIdToIndex,
2626 dispatchedGestureIdBits, -1, 0, 0,
2627 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002628
2629 dispatchedGestureIdBits.clear();
2630 } else {
2631 BitSet32 upGestureIdBits;
2632 if (finishPreviousGesture) {
2633 upGestureIdBits = dispatchedGestureIdBits;
2634 } else {
2635 upGestureIdBits.value =
2636 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2637 }
2638 while (!upGestureIdBits.isEmpty()) {
2639 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2640
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002641 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2642 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2643 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2644 mPointerGesture.lastGestureProperties,
2645 mPointerGesture.lastGestureCoords,
2646 mPointerGesture.lastGestureIdToIndex,
2647 dispatchedGestureIdBits, id, 0, 0,
2648 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002649
2650 dispatchedGestureIdBits.clearBit(id);
2651 }
2652 }
2653 }
2654
2655 // Send motion events for all pointers that moved.
2656 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002657 out.push_back(
2658 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2659 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2660 mPointerGesture.currentGestureProperties,
2661 mPointerGesture.currentGestureCoords,
2662 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2663 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002664 }
2665
2666 // Send motion events for all pointers that went down.
2667 if (down) {
2668 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2669 ~dispatchedGestureIdBits.value);
2670 while (!downGestureIdBits.isEmpty()) {
2671 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2672 dispatchedGestureIdBits.markBit(id);
2673
2674 if (dispatchedGestureIdBits.count() == 1) {
2675 mPointerGesture.downTime = when;
2676 }
2677
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002678 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2679 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2680 buttonState, 0, mPointerGesture.currentGestureProperties,
2681 mPointerGesture.currentGestureCoords,
2682 mPointerGesture.currentGestureIdToIndex,
2683 dispatchedGestureIdBits, id, 0, 0,
2684 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002685 }
2686 }
2687
2688 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002689 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002690 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2691 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2692 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2693 mPointerGesture.currentGestureProperties,
2694 mPointerGesture.currentGestureCoords,
2695 mPointerGesture.currentGestureIdToIndex,
2696 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2697 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002698 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2699 // Synthesize a hover move event after all pointers go up to indicate that
2700 // the pointer is hovering again even if the user is not currently touching
2701 // the touch pad. This ensures that a view will receive a fresh hover enter
2702 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002703 float x, y;
2704 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002705
2706 PointerProperties pointerProperties;
2707 pointerProperties.clear();
2708 pointerProperties.id = 0;
2709 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2710
2711 PointerCoords pointerCoords;
2712 pointerCoords.clear();
2713 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2714 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2715
2716 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002717 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2718 mSource, displayId, policyFlags,
2719 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2720 buttonState, MotionClassification::NONE,
2721 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2722 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2723 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002724 }
2725
2726 // Update state.
2727 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2728 if (!down) {
2729 mPointerGesture.lastGestureIdBits.clear();
2730 } else {
2731 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2732 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2733 uint32_t id = idBits.clearFirstMarkedBit();
2734 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2735 mPointerGesture.lastGestureProperties[index].copyFrom(
2736 mPointerGesture.currentGestureProperties[index]);
2737 mPointerGesture.lastGestureCoords[index].copyFrom(
2738 mPointerGesture.currentGestureCoords[index]);
2739 mPointerGesture.lastGestureIdToIndex[id] = index;
2740 }
2741 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002742 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002743}
2744
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002745std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2746 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002747 const MotionClassification classification =
2748 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2749 ? MotionClassification::TWO_FINGER_SWIPE
2750 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002751 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002752 // Cancel previously dispatches pointers.
2753 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2754 int32_t metaState = getContext()->getGlobalMetaState();
2755 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002756 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2757 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
2758 AMOTION_EVENT_EDGE_FLAG_NONE,
2759 mPointerGesture.lastGestureProperties,
2760 mPointerGesture.lastGestureCoords,
2761 mPointerGesture.lastGestureIdToIndex,
2762 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2763 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002764 }
2765
2766 // Reset the current pointer gesture.
2767 mPointerGesture.reset();
2768 mPointerVelocityControl.reset();
2769
2770 // Remove any current spots.
2771 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002772 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002773 mPointerController->clearSpots();
2774 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002775 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002776}
2777
2778bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2779 bool* outFinishPreviousGesture, bool isTimeout) {
2780 *outCancelPreviousGesture = false;
2781 *outFinishPreviousGesture = false;
2782
2783 // Handle TAP timeout.
2784 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002785 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002786
Michael Wright227c5542020-07-02 18:30:52 +01002787 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2789 // The tap/drag timeout has not yet expired.
2790 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2791 mConfig.pointerGestureTapDragInterval);
2792 } else {
2793 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002794 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 *outFinishPreviousGesture = true;
2796
2797 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002798 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002799 mPointerGesture.currentGestureIdBits.clear();
2800
2801 mPointerVelocityControl.reset();
2802 return true;
2803 }
2804 }
2805
2806 // We did not handle this timeout.
2807 return false;
2808 }
2809
2810 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2811 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2812
2813 // Update the velocity tracker.
2814 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002815 std::vector<float> positionsX;
2816 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002817 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002818 uint32_t id = idBits.clearFirstMarkedBit();
2819 const RawPointerData::Pointer& pointer =
2820 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002821 positionsX.push_back(pointer.x * mPointerXMovementScale);
2822 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823 }
2824 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002825 {{AMOTION_EVENT_AXIS_X, positionsX},
2826 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002827 }
2828
2829 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2830 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002831 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2832 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2833 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002834 mPointerGesture.resetTap();
2835 }
2836
2837 // Pick a new active touch id if needed.
2838 // Choose an arbitrary pointer that just went down, if there is one.
2839 // Otherwise choose an arbitrary remaining pointer.
2840 // This guarantees we always have an active touch id when there is at least one pointer.
2841 // We keep the same active touch id for as long as possible.
2842 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2843 int32_t activeTouchId = lastActiveTouchId;
2844 if (activeTouchId < 0) {
2845 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2846 activeTouchId = mPointerGesture.activeTouchId =
2847 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2848 mPointerGesture.firstTouchTime = when;
2849 }
2850 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2851 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2852 activeTouchId = mPointerGesture.activeTouchId =
2853 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2854 } else {
2855 activeTouchId = mPointerGesture.activeTouchId = -1;
2856 }
2857 }
2858
2859 // Determine whether we are in quiet time.
2860 bool isQuietTime = false;
2861 if (activeTouchId < 0) {
2862 mPointerGesture.resetQuietTime();
2863 } else {
2864 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2865 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002866 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2867 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2868 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869 currentFingerCount < 2) {
2870 // Enter quiet time when exiting swipe or freeform state.
2871 // This is to prevent accidentally entering the hover state and flinging the
2872 // pointer when finishing a swipe and there is still one pointer left onscreen.
2873 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002874 } else if (mPointerGesture.lastGestureMode ==
2875 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002876 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2877 // Enter quiet time when releasing the button and there are still two or more
2878 // fingers down. This may indicate that one finger was used to press the button
2879 // but it has not gone up yet.
2880 isQuietTime = true;
2881 }
2882 if (isQuietTime) {
2883 mPointerGesture.quietTime = when;
2884 }
2885 }
2886 }
2887
2888 // Switch states based on button and pointer state.
2889 if (isQuietTime) {
2890 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002891 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2892 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2893 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002894 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 *outFinishPreviousGesture = true;
2896 }
2897
2898 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002899 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002900 mPointerGesture.currentGestureIdBits.clear();
2901
2902 mPointerVelocityControl.reset();
2903 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2904 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2905 // The pointer follows the active touch point.
2906 // Emit DOWN, MOVE, UP events at the pointer location.
2907 //
2908 // Only the active touch matters; other fingers are ignored. This policy helps
2909 // to handle the case where the user places a second finger on the touch pad
2910 // to apply the necessary force to depress an integrated button below the surface.
2911 // We don't want the second finger to be delivered to applications.
2912 //
2913 // For this to work well, we need to make sure to track the pointer that is really
2914 // active. If the user first puts one finger down to click then adds another
2915 // finger to drag then the active pointer should switch to the finger that is
2916 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002917 ALOGD_IF(DEBUG_GESTURES,
2918 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2919 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002921 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 *outFinishPreviousGesture = true;
2923 mPointerGesture.activeGestureId = 0;
2924 }
2925
2926 // Switch pointers if needed.
2927 // Find the fastest pointer and follow it.
2928 if (activeTouchId >= 0 && currentFingerCount > 1) {
2929 int32_t bestId = -1;
2930 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2931 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2932 uint32_t id = idBits.clearFirstMarkedBit();
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002933 std::optional<float> vx =
2934 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
2935 std::optional<float> vy =
2936 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
2937 if (vx && vy) {
2938 float speed = hypotf(*vx, *vy);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 if (speed > bestSpeed) {
2940 bestId = id;
2941 bestSpeed = speed;
2942 }
2943 }
2944 }
2945 if (bestId >= 0 && bestId != activeTouchId) {
2946 mPointerGesture.activeTouchId = activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002947 ALOGD_IF(DEBUG_GESTURES,
2948 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2949 "bestSpeed=%0.3f",
2950 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 }
2952 }
2953
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002955 // When using spots, the click will occur at the position of the anchor
2956 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002957 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958 } else {
2959 mPointerVelocityControl.reset();
2960 }
2961
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002962 float x, y;
2963 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002964
Michael Wright227c5542020-07-02 18:30:52 +01002965 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002966 mPointerGesture.currentGestureIdBits.clear();
2967 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2968 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2969 mPointerGesture.currentGestureProperties[0].clear();
2970 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2971 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2972 mPointerGesture.currentGestureCoords[0].clear();
2973 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2974 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2975 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2976 } else if (currentFingerCount == 0) {
2977 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002978 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979 *outFinishPreviousGesture = true;
2980 }
2981
2982 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2983 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2984 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002985 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2986 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002987 lastFingerCount == 1) {
2988 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002989 float x, y;
2990 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2992 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002993 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002994
2995 mPointerGesture.tapUpTime = when;
2996 getContext()->requestTimeoutAtTime(when +
2997 mConfig.pointerGestureTapDragInterval);
2998
2999 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01003000 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003001 mPointerGesture.currentGestureIdBits.clear();
3002 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3003 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3004 mPointerGesture.currentGestureProperties[0].clear();
3005 mPointerGesture.currentGestureProperties[0].id =
3006 mPointerGesture.activeGestureId;
3007 mPointerGesture.currentGestureProperties[0].toolType =
3008 AMOTION_EVENT_TOOL_TYPE_FINGER;
3009 mPointerGesture.currentGestureCoords[0].clear();
3010 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3011 mPointerGesture.tapX);
3012 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3013 mPointerGesture.tapY);
3014 mPointerGesture.currentGestureCoords[0]
3015 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3016
3017 tapped = true;
3018 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003019 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
3020 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003021 }
3022 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003023 if (DEBUG_GESTURES) {
3024 if (mPointerGesture.tapDownTime != LLONG_MIN) {
3025 ALOGD("Gestures: Not a TAP, %0.3fms since down",
3026 (when - mPointerGesture.tapDownTime) * 0.000001f);
3027 } else {
3028 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
3029 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003030 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003031 }
3032 }
3033
3034 mPointerVelocityControl.reset();
3035
3036 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00003037 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003038 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01003039 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003040 mPointerGesture.currentGestureIdBits.clear();
3041 }
3042 } else if (currentFingerCount == 1) {
3043 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3044 // The pointer follows the active touch point.
3045 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3046 // When in TAP_DRAG, emit MOVE events at the pointer location.
3047 ALOG_ASSERT(activeTouchId >= 0);
3048
Michael Wright227c5542020-07-02 18:30:52 +01003049 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3050 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003051 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003052 float x, y;
3053 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003054 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3055 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003056 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003057 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003058 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3059 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003060 }
3061 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003062 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3063 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003064 }
Michael Wright227c5542020-07-02 18:30:52 +01003065 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3066 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003067 }
3068
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003069 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003070 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003071 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003072 } else {
3073 mPointerVelocityControl.reset();
3074 }
3075
3076 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003077 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003078 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003079 down = true;
3080 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003081 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003082 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003083 *outFinishPreviousGesture = true;
3084 }
3085 mPointerGesture.activeGestureId = 0;
3086 down = false;
3087 }
3088
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003089 float x, y;
3090 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003091
3092 mPointerGesture.currentGestureIdBits.clear();
3093 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3094 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3095 mPointerGesture.currentGestureProperties[0].clear();
3096 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3097 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3098 mPointerGesture.currentGestureCoords[0].clear();
3099 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3100 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3101 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3102 down ? 1.0f : 0.0f);
3103
3104 if (lastFingerCount == 0 && currentFingerCount != 0) {
3105 mPointerGesture.resetTap();
3106 mPointerGesture.tapDownTime = when;
3107 mPointerGesture.tapX = x;
3108 mPointerGesture.tapY = y;
3109 }
3110 } else {
3111 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3112 // We need to provide feedback for each finger that goes down so we cannot wait
3113 // for the fingers to move before deciding what to do.
3114 //
3115 // The ambiguous case is deciding what to do when there are two fingers down but they
3116 // have not moved enough to determine whether they are part of a drag or part of a
3117 // freeform gesture, or just a press or long-press at the pointer location.
3118 //
3119 // When there are two fingers we start with the PRESS hypothesis and we generate a
3120 // down at the pointer location.
3121 //
3122 // When the two fingers move enough or when additional fingers are added, we make
3123 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3124 ALOG_ASSERT(activeTouchId >= 0);
3125
3126 bool settled = when >=
3127 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003128 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3129 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3130 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003131 *outFinishPreviousGesture = true;
3132 } else if (!settled && currentFingerCount > lastFingerCount) {
3133 // Additional pointers have gone down but not yet settled.
3134 // Reset the gesture.
Harry Cutts45483602022-08-24 14:36:48 +00003135 ALOGD_IF(DEBUG_GESTURES,
3136 "Gestures: Resetting gesture since additional pointers went down for "
3137 "MULTITOUCH, settle time remaining %0.3fms",
3138 (mPointerGesture.firstTouchTime +
3139 mConfig.pointerGestureMultitouchSettleInterval - when) *
3140 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003141 *outCancelPreviousGesture = true;
3142 } else {
3143 // Continue previous gesture.
3144 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3145 }
3146
3147 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003148 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003149 mPointerGesture.activeGestureId = 0;
3150 mPointerGesture.referenceIdBits.clear();
3151 mPointerVelocityControl.reset();
3152
3153 // Use the centroid and pointer location as the reference points for the gesture.
Harry Cutts45483602022-08-24 14:36:48 +00003154 ALOGD_IF(DEBUG_GESTURES,
3155 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3156 "%0.3fms",
3157 (mPointerGesture.firstTouchTime +
3158 mConfig.pointerGestureMultitouchSettleInterval - when) *
3159 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003160 mCurrentRawState.rawPointerData
3161 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3162 &mPointerGesture.referenceTouchY);
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003163 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3164 &mPointerGesture.referenceGestureY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003165 }
3166
3167 // Clear the reference deltas for fingers not yet included in the reference calculation.
3168 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3169 ~mPointerGesture.referenceIdBits.value);
3170 !idBits.isEmpty();) {
3171 uint32_t id = idBits.clearFirstMarkedBit();
3172 mPointerGesture.referenceDeltas[id].dx = 0;
3173 mPointerGesture.referenceDeltas[id].dy = 0;
3174 }
3175 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3176
3177 // Add delta for all fingers and calculate a common movement delta.
3178 float commonDeltaX = 0, commonDeltaY = 0;
3179 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3180 mCurrentCookedState.fingerIdBits.value);
3181 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3182 bool first = (idBits == commonIdBits);
3183 uint32_t id = idBits.clearFirstMarkedBit();
3184 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3185 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3186 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3187 delta.dx += cpd.x - lpd.x;
3188 delta.dy += cpd.y - lpd.y;
3189
3190 if (first) {
3191 commonDeltaX = delta.dx;
3192 commonDeltaY = delta.dy;
3193 } else {
3194 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3195 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3196 }
3197 }
3198
3199 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003200 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003201 float dist[MAX_POINTER_ID + 1];
3202 int32_t distOverThreshold = 0;
3203 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3204 uint32_t id = idBits.clearFirstMarkedBit();
3205 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3206 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3207 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3208 distOverThreshold += 1;
3209 }
3210 }
3211
3212 // Only transition when at least two pointers have moved further than
3213 // the minimum distance threshold.
3214 if (distOverThreshold >= 2) {
3215 if (currentFingerCount > 2) {
3216 // There are more than two pointers, switch to FREEFORM.
Harry Cutts45483602022-08-24 14:36:48 +00003217 ALOGD_IF(DEBUG_GESTURES,
3218 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3219 currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003220 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003221 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003222 } else {
3223 // There are exactly two pointers.
3224 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3225 uint32_t id1 = idBits.clearFirstMarkedBit();
3226 uint32_t id2 = idBits.firstMarkedBit();
3227 const RawPointerData::Pointer& p1 =
3228 mCurrentRawState.rawPointerData.pointerForId(id1);
3229 const RawPointerData::Pointer& p2 =
3230 mCurrentRawState.rawPointerData.pointerForId(id2);
3231 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3232 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3233 // There are two pointers but they are too far apart for a SWIPE,
3234 // switch to FREEFORM.
Harry Cutts45483602022-08-24 14:36:48 +00003235 ALOGD_IF(DEBUG_GESTURES,
3236 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3237 mutualDistance, mPointerGestureMaxSwipeWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003238 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003239 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003240 } else {
3241 // There are two pointers. Wait for both pointers to start moving
3242 // before deciding whether this is a SWIPE or FREEFORM gesture.
3243 float dist1 = dist[id1];
3244 float dist2 = dist[id2];
3245 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3246 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3247 // Calculate the dot product of the displacement vectors.
3248 // When the vectors are oriented in approximately the same direction,
3249 // the angle betweeen them is near zero and the cosine of the angle
3250 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3251 // mag(v2).
3252 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3253 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3254 float dx1 = delta1.dx * mPointerXZoomScale;
3255 float dy1 = delta1.dy * mPointerYZoomScale;
3256 float dx2 = delta2.dx * mPointerXZoomScale;
3257 float dy2 = delta2.dy * mPointerYZoomScale;
3258 float dot = dx1 * dx2 + dy1 * dy2;
3259 float cosine = dot / (dist1 * dist2); // denominator always > 0
3260 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3261 // Pointers are moving in the same direction. Switch to SWIPE.
Harry Cutts45483602022-08-24 14:36:48 +00003262 ALOGD_IF(DEBUG_GESTURES,
3263 "Gestures: PRESS transitioned to SWIPE, "
3264 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3265 "cosine %0.3f >= %0.3f",
3266 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3267 mConfig.pointerGestureMultitouchMinDistance, cosine,
3268 mConfig.pointerGestureSwipeTransitionAngleCosine);
Michael Wright227c5542020-07-02 18:30:52 +01003269 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003270 } else {
3271 // Pointers are moving in different directions. Switch to FREEFORM.
Harry Cutts45483602022-08-24 14:36:48 +00003272 ALOGD_IF(DEBUG_GESTURES,
3273 "Gestures: PRESS transitioned to FREEFORM, "
3274 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3275 "cosine %0.3f < %0.3f",
3276 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3277 mConfig.pointerGestureMultitouchMinDistance, cosine,
3278 mConfig.pointerGestureSwipeTransitionAngleCosine);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003279 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003280 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003281 }
3282 }
3283 }
3284 }
3285 }
Michael Wright227c5542020-07-02 18:30:52 +01003286 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003287 // Switch from SWIPE to FREEFORM if additional pointers go down.
3288 // Cancel previous gesture.
3289 if (currentFingerCount > 2) {
Harry Cutts45483602022-08-24 14:36:48 +00003290 ALOGD_IF(DEBUG_GESTURES,
3291 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3292 currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003293 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003294 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003295 }
3296 }
3297
3298 // Move the reference points based on the overall group motion of the fingers
3299 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003300 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003301 (commonDeltaX || commonDeltaY)) {
3302 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3303 uint32_t id = idBits.clearFirstMarkedBit();
3304 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3305 delta.dx = 0;
3306 delta.dy = 0;
3307 }
3308
3309 mPointerGesture.referenceTouchX += commonDeltaX;
3310 mPointerGesture.referenceTouchY += commonDeltaY;
3311
3312 commonDeltaX *= mPointerXMovementScale;
3313 commonDeltaY *= mPointerYMovementScale;
3314
Prabir Pradhan1728b212021-10-19 16:00:03 -07003315 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003316 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3317
3318 mPointerGesture.referenceGestureX += commonDeltaX;
3319 mPointerGesture.referenceGestureY += commonDeltaY;
3320 }
3321
3322 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003323 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3324 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003325 // PRESS or SWIPE mode.
Harry Cutts45483602022-08-24 14:36:48 +00003326 ALOGD_IF(DEBUG_GESTURES,
3327 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3328 "currentTouchPointerCount=%d",
3329 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003330 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3331
3332 mPointerGesture.currentGestureIdBits.clear();
3333 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3334 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3335 mPointerGesture.currentGestureProperties[0].clear();
3336 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3337 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3338 mPointerGesture.currentGestureCoords[0].clear();
3339 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3340 mPointerGesture.referenceGestureX);
3341 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3342 mPointerGesture.referenceGestureY);
3343 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003344 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003345 // FREEFORM mode.
Harry Cutts45483602022-08-24 14:36:48 +00003346 ALOGD_IF(DEBUG_GESTURES,
3347 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3348 "currentTouchPointerCount=%d",
3349 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003350 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3351
3352 mPointerGesture.currentGestureIdBits.clear();
3353
3354 BitSet32 mappedTouchIdBits;
3355 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003356 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003357 // Initially, assign the active gesture id to the active touch point
3358 // if there is one. No other touch id bits are mapped yet.
3359 if (!*outCancelPreviousGesture) {
3360 mappedTouchIdBits.markBit(activeTouchId);
3361 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3362 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3363 mPointerGesture.activeGestureId;
3364 } else {
3365 mPointerGesture.activeGestureId = -1;
3366 }
3367 } else {
3368 // Otherwise, assume we mapped all touches from the previous frame.
3369 // Reuse all mappings that are still applicable.
3370 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3371 mCurrentCookedState.fingerIdBits.value;
3372 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3373
3374 // Check whether we need to choose a new active gesture id because the
3375 // current went went up.
3376 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3377 ~mCurrentCookedState.fingerIdBits.value);
3378 !upTouchIdBits.isEmpty();) {
3379 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3380 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3381 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3382 mPointerGesture.activeGestureId = -1;
3383 break;
3384 }
3385 }
3386 }
3387
Harry Cutts45483602022-08-24 14:36:48 +00003388 ALOGD_IF(DEBUG_GESTURES,
3389 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, "
3390 "usedGestureIdBits=0x%08x, activeGestureId=%d",
3391 mappedTouchIdBits.value, usedGestureIdBits.value,
3392 mPointerGesture.activeGestureId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003393
3394 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3395 for (uint32_t i = 0; i < currentFingerCount; i++) {
3396 uint32_t touchId = idBits.clearFirstMarkedBit();
3397 uint32_t gestureId;
3398 if (!mappedTouchIdBits.hasBit(touchId)) {
3399 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3400 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
Harry Cutts45483602022-08-24 14:36:48 +00003401 ALOGD_IF(DEBUG_GESTURES,
3402 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d",
3403 touchId, gestureId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003404 } else {
3405 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
Harry Cutts45483602022-08-24 14:36:48 +00003406 ALOGD_IF(DEBUG_GESTURES,
3407 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3408 touchId, gestureId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003409 }
3410 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3411 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3412
3413 const RawPointerData::Pointer& pointer =
3414 mCurrentRawState.rawPointerData.pointerForId(touchId);
3415 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3416 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07003417 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003418
3419 mPointerGesture.currentGestureProperties[i].clear();
3420 mPointerGesture.currentGestureProperties[i].id = gestureId;
3421 mPointerGesture.currentGestureProperties[i].toolType =
3422 AMOTION_EVENT_TOOL_TYPE_FINGER;
3423 mPointerGesture.currentGestureCoords[i].clear();
3424 mPointerGesture.currentGestureCoords[i]
3425 .setAxisValue(AMOTION_EVENT_AXIS_X,
3426 mPointerGesture.referenceGestureX + deltaX);
3427 mPointerGesture.currentGestureCoords[i]
3428 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3429 mPointerGesture.referenceGestureY + deltaY);
3430 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3431 1.0f);
3432 }
3433
3434 if (mPointerGesture.activeGestureId < 0) {
3435 mPointerGesture.activeGestureId =
3436 mPointerGesture.currentGestureIdBits.firstMarkedBit();
Harry Cutts45483602022-08-24 14:36:48 +00003437 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3438 mPointerGesture.activeGestureId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003439 }
3440 }
3441 }
3442
3443 mPointerController->setButtonState(mCurrentRawState.buttonState);
3444
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003445 if (DEBUG_GESTURES) {
3446 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3447 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3448 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3449 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3450 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3451 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3452 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3453 uint32_t id = idBits.clearFirstMarkedBit();
3454 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3455 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3456 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3457 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3458 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3459 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3460 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3461 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3462 }
3463 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3464 uint32_t id = idBits.clearFirstMarkedBit();
3465 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3466 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3467 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3468 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3469 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3470 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3471 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3472 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3473 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003474 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003475 return true;
3476}
3477
Harry Cutts714d1ad2022-08-24 16:36:43 +00003478void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3479 const RawPointerData::Pointer& currentPointer =
3480 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3481 const RawPointerData::Pointer& lastPointer =
3482 mLastRawState.rawPointerData.pointerForId(pointerId);
3483 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3484 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3485
3486 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3487 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3488
3489 mPointerController->move(deltaX, deltaY);
3490}
3491
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003492std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3493 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003494 mPointerSimple.currentCoords.clear();
3495 mPointerSimple.currentProperties.clear();
3496
3497 bool down, hovering;
3498 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3499 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3500 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003501 mPointerController
3502 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3503 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003504
3505 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3506 down = !hovering;
3507
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003508 float x, y;
3509 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003510 mPointerSimple.currentCoords.copyFrom(
3511 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3512 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3513 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3514 mPointerSimple.currentProperties.id = 0;
3515 mPointerSimple.currentProperties.toolType =
3516 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3517 } else {
3518 down = false;
3519 hovering = false;
3520 }
3521
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003522 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003523}
3524
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003525std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3526 uint32_t policyFlags) {
3527 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003528}
3529
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003530std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3531 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003532 mPointerSimple.currentCoords.clear();
3533 mPointerSimple.currentProperties.clear();
3534
3535 bool down, hovering;
3536 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3537 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003538 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003539 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003540 } else {
3541 mPointerVelocityControl.reset();
3542 }
3543
3544 down = isPointerDown(mCurrentRawState.buttonState);
3545 hovering = !down;
3546
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003547 float x, y;
3548 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003549 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003550 mPointerSimple.currentCoords.copyFrom(
3551 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3552 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3553 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3554 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3555 hovering ? 0.0f : 1.0f);
3556 mPointerSimple.currentProperties.id = 0;
3557 mPointerSimple.currentProperties.toolType =
3558 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3559 } else {
3560 mPointerVelocityControl.reset();
3561
3562 down = false;
3563 hovering = false;
3564 }
3565
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003566 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567}
3568
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003569std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3570 uint32_t policyFlags) {
3571 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572
3573 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003574
3575 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003576}
3577
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003578std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3579 uint32_t policyFlags, bool down,
3580 bool hovering) {
3581 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003582 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003583
3584 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003585 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003586 mPointerController->clearSpots();
3587 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003588 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003590 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003591 }
Garfield Tan9514d782020-11-10 16:37:23 -08003592 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003594 float xCursorPosition, yCursorPosition;
3595 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003596
3597 if (mPointerSimple.down && !down) {
3598 mPointerSimple.down = false;
3599
3600 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003601 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3602 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3603 0, metaState, mLastRawState.buttonState,
3604 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3605 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3606 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3607 yCursorPosition, mPointerSimple.downTime,
3608 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003609 }
3610
3611 if (mPointerSimple.hovering && !hovering) {
3612 mPointerSimple.hovering = false;
3613
3614 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003615 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3616 mSource, displayId, policyFlags,
3617 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3618 mLastRawState.buttonState, MotionClassification::NONE,
3619 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3620 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3621 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3622 yCursorPosition, mPointerSimple.downTime,
3623 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003624 }
3625
3626 if (down) {
3627 if (!mPointerSimple.down) {
3628 mPointerSimple.down = true;
3629 mPointerSimple.downTime = when;
3630
3631 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003632 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3633 mSource, displayId, policyFlags,
3634 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3635 mCurrentRawState.buttonState, MotionClassification::NONE,
3636 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3637 &mPointerSimple.currentProperties,
3638 &mPointerSimple.currentCoords, mOrientedXPrecision,
3639 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3640 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003641 }
3642
3643 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003644 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3645 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3646 0, 0, metaState, mCurrentRawState.buttonState,
3647 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3648 &mPointerSimple.currentProperties,
3649 &mPointerSimple.currentCoords, mOrientedXPrecision,
3650 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3651 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003652 }
3653
3654 if (hovering) {
3655 if (!mPointerSimple.hovering) {
3656 mPointerSimple.hovering = true;
3657
3658 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003659 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3660 mSource, displayId, policyFlags,
3661 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3662 mCurrentRawState.buttonState, MotionClassification::NONE,
3663 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3664 &mPointerSimple.currentProperties,
3665 &mPointerSimple.currentCoords, mOrientedXPrecision,
3666 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3667 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003668 }
3669
3670 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003671 out.push_back(
3672 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3673 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3674 metaState, mCurrentRawState.buttonState,
3675 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3676 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3677 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3678 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003679 }
3680
3681 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3682 float vscroll = mCurrentRawState.rawVScroll;
3683 float hscroll = mCurrentRawState.rawHScroll;
3684 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3685 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3686
3687 // Send scroll.
3688 PointerCoords pointerCoords;
3689 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3690 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3691 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3692
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003693 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3694 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3695 0, 0, metaState, mCurrentRawState.buttonState,
3696 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3697 &mPointerSimple.currentProperties, &pointerCoords,
3698 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3699 yCursorPosition, mPointerSimple.downTime,
3700 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003701 }
3702
3703 // Save state.
3704 if (down || hovering) {
3705 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3706 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3707 } else {
3708 mPointerSimple.reset();
3709 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003710 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003711}
3712
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003713std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3714 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003715 mPointerSimple.currentCoords.clear();
3716 mPointerSimple.currentProperties.clear();
3717
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003718 return dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003719}
3720
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003721NotifyMotionArgs TouchInputMapper::dispatchMotion(
3722 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3723 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
3724 int32_t edgeFlags, const PointerProperties* properties, const PointerCoords* coords,
3725 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
3726 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003727 PointerCoords pointerCoords[MAX_POINTERS];
3728 PointerProperties pointerProperties[MAX_POINTERS];
3729 uint32_t pointerCount = 0;
3730 while (!idBits.isEmpty()) {
3731 uint32_t id = idBits.clearFirstMarkedBit();
3732 uint32_t index = idToIndex[id];
3733 pointerProperties[pointerCount].copyFrom(properties[index]);
3734 pointerCoords[pointerCount].copyFrom(coords[index]);
3735
3736 if (changedId >= 0 && id == uint32_t(changedId)) {
3737 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3738 }
3739
3740 pointerCount += 1;
3741 }
3742
3743 ALOG_ASSERT(pointerCount != 0);
3744
3745 if (changedId >= 0 && pointerCount == 1) {
3746 // Replace initial down and final up action.
3747 // We can compare the action without masking off the changed pointer index
3748 // because we know the index is 0.
3749 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3750 action = AMOTION_EVENT_ACTION_DOWN;
3751 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003752 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3753 action = AMOTION_EVENT_ACTION_CANCEL;
3754 } else {
3755 action = AMOTION_EVENT_ACTION_UP;
3756 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003757 } else {
3758 // Can't happen.
3759 ALOG_ASSERT(false);
3760 }
3761 }
3762 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3763 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003764 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003765 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003766 }
3767 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3768 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003769 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003770 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003771 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003772 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3773 policyFlags, action, actionButton, flags, metaState, buttonState,
3774 classification, edgeFlags, pointerCount, pointerProperties,
3775 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3776 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003777}
3778
3779bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3780 const PointerCoords* inCoords,
3781 const uint32_t* inIdToIndex,
3782 PointerProperties* outProperties,
3783 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3784 BitSet32 idBits) const {
3785 bool changed = false;
3786 while (!idBits.isEmpty()) {
3787 uint32_t id = idBits.clearFirstMarkedBit();
3788 uint32_t inIndex = inIdToIndex[id];
3789 uint32_t outIndex = outIdToIndex[id];
3790
3791 const PointerProperties& curInProperties = inProperties[inIndex];
3792 const PointerCoords& curInCoords = inCoords[inIndex];
3793 PointerProperties& curOutProperties = outProperties[outIndex];
3794 PointerCoords& curOutCoords = outCoords[outIndex];
3795
3796 if (curInProperties != curOutProperties) {
3797 curOutProperties.copyFrom(curInProperties);
3798 changed = true;
3799 }
3800
3801 if (curInCoords != curOutCoords) {
3802 curOutCoords.copyFrom(curInCoords);
3803 changed = true;
3804 }
3805 }
3806 return changed;
3807}
3808
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003809std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3810 std::list<NotifyArgs> out;
3811 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3812 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3813 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003814}
3815
Prabir Pradhan1728b212021-10-19 16:00:03 -07003816// Transform input device coordinates to display panel coordinates.
3817void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003818 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3819 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3820
arthurhunga36b28e2020-12-29 20:28:15 +08003821 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3822 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3823
Prabir Pradhan1728b212021-10-19 16:00:03 -07003824 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003825 // 0 - no swap and reverse.
3826 // 90 - swap x/y and reverse y.
3827 // 180 - reverse x, y.
3828 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003829 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003830 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003831 x = xScaled;
3832 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003833 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003834 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003835 y = xScaledMax;
3836 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003837 break;
3838 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003839 x = xScaledMax;
3840 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003841 break;
3842 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003843 y = xScaled;
3844 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003845 break;
3846 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003847 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003848 }
3849}
3850
Prabir Pradhan1728b212021-10-19 16:00:03 -07003851bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003852 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3853 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3854
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003855 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003856 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003857 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003858 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003859}
3860
3861const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3862 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003863 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3864 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3865 "left=%d, top=%d, right=%d, bottom=%d",
3866 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3867 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003868
3869 if (virtualKey.isHit(x, y)) {
3870 return &virtualKey;
3871 }
3872 }
3873
3874 return nullptr;
3875}
3876
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003877void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3878 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3879 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003880
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003881 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003882
3883 if (currentPointerCount == 0) {
3884 // No pointers to assign.
3885 return;
3886 }
3887
3888 if (lastPointerCount == 0) {
3889 // All pointers are new.
3890 for (uint32_t i = 0; i < currentPointerCount; i++) {
3891 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003892 current.rawPointerData.pointers[i].id = id;
3893 current.rawPointerData.idToIndex[id] = i;
3894 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003895 }
3896 return;
3897 }
3898
3899 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003900 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003901 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003902 uint32_t id = last.rawPointerData.pointers[0].id;
3903 current.rawPointerData.pointers[0].id = id;
3904 current.rawPointerData.idToIndex[id] = 0;
3905 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003906 return;
3907 }
3908
3909 // General case.
3910 // We build a heap of squared euclidean distances between current and last pointers
3911 // associated with the current and last pointer indices. Then, we find the best
3912 // match (by distance) for each current pointer.
3913 // The pointers must have the same tool type but it is possible for them to
3914 // transition from hovering to touching or vice-versa while retaining the same id.
3915 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3916
3917 uint32_t heapSize = 0;
3918 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3919 currentPointerIndex++) {
3920 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3921 lastPointerIndex++) {
3922 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003923 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003924 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003925 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003926 if (currentPointer.toolType == lastPointer.toolType) {
3927 int64_t deltaX = currentPointer.x - lastPointer.x;
3928 int64_t deltaY = currentPointer.y - lastPointer.y;
3929
3930 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3931
3932 // Insert new element into the heap (sift up).
3933 heap[heapSize].currentPointerIndex = currentPointerIndex;
3934 heap[heapSize].lastPointerIndex = lastPointerIndex;
3935 heap[heapSize].distance = distance;
3936 heapSize += 1;
3937 }
3938 }
3939 }
3940
3941 // Heapify
3942 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3943 startIndex -= 1;
3944 for (uint32_t parentIndex = startIndex;;) {
3945 uint32_t childIndex = parentIndex * 2 + 1;
3946 if (childIndex >= heapSize) {
3947 break;
3948 }
3949
3950 if (childIndex + 1 < heapSize &&
3951 heap[childIndex + 1].distance < heap[childIndex].distance) {
3952 childIndex += 1;
3953 }
3954
3955 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3956 break;
3957 }
3958
3959 swap(heap[parentIndex], heap[childIndex]);
3960 parentIndex = childIndex;
3961 }
3962 }
3963
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003964 if (DEBUG_POINTER_ASSIGNMENT) {
3965 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3966 for (size_t i = 0; i < heapSize; i++) {
3967 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3968 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3969 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003970 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003971
3972 // Pull matches out by increasing order of distance.
3973 // To avoid reassigning pointers that have already been matched, the loop keeps track
3974 // of which last and current pointers have been matched using the matchedXXXBits variables.
3975 // It also tracks the used pointer id bits.
3976 BitSet32 matchedLastBits(0);
3977 BitSet32 matchedCurrentBits(0);
3978 BitSet32 usedIdBits(0);
3979 bool first = true;
3980 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3981 while (heapSize > 0) {
3982 if (first) {
3983 // The first time through the loop, we just consume the root element of
3984 // the heap (the one with smallest distance).
3985 first = false;
3986 } else {
3987 // Previous iterations consumed the root element of the heap.
3988 // Pop root element off of the heap (sift down).
3989 heap[0] = heap[heapSize];
3990 for (uint32_t parentIndex = 0;;) {
3991 uint32_t childIndex = parentIndex * 2 + 1;
3992 if (childIndex >= heapSize) {
3993 break;
3994 }
3995
3996 if (childIndex + 1 < heapSize &&
3997 heap[childIndex + 1].distance < heap[childIndex].distance) {
3998 childIndex += 1;
3999 }
4000
4001 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4002 break;
4003 }
4004
4005 swap(heap[parentIndex], heap[childIndex]);
4006 parentIndex = childIndex;
4007 }
4008
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004009 if (DEBUG_POINTER_ASSIGNMENT) {
4010 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4011 for (size_t j = 0; j < heapSize; j++) {
4012 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4013 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4014 heap[j].distance);
4015 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004016 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004017 }
4018
4019 heapSize -= 1;
4020
4021 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4022 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4023
4024 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4025 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4026
4027 matchedCurrentBits.markBit(currentPointerIndex);
4028 matchedLastBits.markBit(lastPointerIndex);
4029
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004030 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4031 current.rawPointerData.pointers[currentPointerIndex].id = id;
4032 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4033 current.rawPointerData.markIdBit(id,
4034 current.rawPointerData.isHovering(
4035 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004036 usedIdBits.markBit(id);
4037
Harry Cutts45483602022-08-24 14:36:48 +00004038 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4039 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4040 ", distance=%" PRIu64,
4041 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004042 break;
4043 }
4044 }
4045
4046 // Assign fresh ids to pointers that were not matched in the process.
4047 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4048 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4049 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4050
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004051 current.rawPointerData.pointers[currentPointerIndex].id = id;
4052 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4053 current.rawPointerData.markIdBit(id,
4054 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004055
Harry Cutts45483602022-08-24 14:36:48 +00004056 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4057 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4058 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004059 }
4060}
4061
4062int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4063 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4064 return AKEY_STATE_VIRTUAL;
4065 }
4066
4067 for (const VirtualKey& virtualKey : mVirtualKeys) {
4068 if (virtualKey.keyCode == keyCode) {
4069 return AKEY_STATE_UP;
4070 }
4071 }
4072
4073 return AKEY_STATE_UNKNOWN;
4074}
4075
4076int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4077 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4078 return AKEY_STATE_VIRTUAL;
4079 }
4080
4081 for (const VirtualKey& virtualKey : mVirtualKeys) {
4082 if (virtualKey.scanCode == scanCode) {
4083 return AKEY_STATE_UP;
4084 }
4085 }
4086
4087 return AKEY_STATE_UNKNOWN;
4088}
4089
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004090bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4091 const std::vector<int32_t>& keyCodes,
4092 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004093 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004094 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004095 if (virtualKey.keyCode == keyCodes[i]) {
4096 outFlags[i] = 1;
4097 }
4098 }
4099 }
4100
4101 return true;
4102}
4103
4104std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4105 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004106 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004107 return std::make_optional(mPointerController->getDisplayId());
4108 } else {
4109 return std::make_optional(mViewport.displayId);
4110 }
4111 }
4112 return std::nullopt;
4113}
4114
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004115} // namespace android