blob: e8cf139e332ea56c0c4a8ed9a1176d0905c2c494 [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
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070076// --- RawPointerData ---
77
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070078void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
79 float x = 0, y = 0;
80 uint32_t count = touchingIdBits.count();
81 if (count) {
82 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
83 uint32_t id = idBits.clearFirstMarkedBit();
84 const Pointer& pointer = pointerForId(id);
85 x += pointer.x;
86 y += pointer.y;
87 }
88 x /= count;
89 y /= count;
90 }
91 *outX = x;
92 *outY = y;
93}
94
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070095// --- TouchInputMapper ---
96
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -080097TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
98 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070099 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100100 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700101 mDisplayWidth(-1),
102 mDisplayHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700103 mPhysicalWidth(-1),
104 mPhysicalHeight(-1),
105 mPhysicalLeft(0),
106 mPhysicalTop(0),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700107 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700108
109TouchInputMapper::~TouchInputMapper() {}
110
Philip Junker4af3b3d2021-12-14 10:36:55 +0100111uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700112 return mSource;
113}
114
115void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
116 InputMapper::populateDeviceInfo(info);
117
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000118 if (mDeviceMode == DeviceMode::DISABLED) {
119 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700120 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000121
122 info->addMotionRange(mOrientedRanges.x);
123 info->addMotionRange(mOrientedRanges.y);
124 info->addMotionRange(mOrientedRanges.pressure);
125
126 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
127 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
128 //
129 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
130 // motion, i.e. the hardware dimensions, as the finger could move completely across the
131 // touchpad in one sample cycle.
132 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
133 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
134 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
135 x.resolution);
136 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
137 y.resolution);
138 }
139
140 if (mOrientedRanges.size) {
141 info->addMotionRange(*mOrientedRanges.size);
142 }
143
144 if (mOrientedRanges.touchMajor) {
145 info->addMotionRange(*mOrientedRanges.touchMajor);
146 info->addMotionRange(*mOrientedRanges.touchMinor);
147 }
148
149 if (mOrientedRanges.toolMajor) {
150 info->addMotionRange(*mOrientedRanges.toolMajor);
151 info->addMotionRange(*mOrientedRanges.toolMinor);
152 }
153
154 if (mOrientedRanges.orientation) {
155 info->addMotionRange(*mOrientedRanges.orientation);
156 }
157
158 if (mOrientedRanges.distance) {
159 info->addMotionRange(*mOrientedRanges.distance);
160 }
161
162 if (mOrientedRanges.tilt) {
163 info->addMotionRange(*mOrientedRanges.tilt);
164 }
165
166 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
167 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
168 }
169 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
170 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
171 }
172 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
173 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
174 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
175 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
176 x.resolution);
177 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
178 y.resolution);
179 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
180 x.resolution);
181 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
182 y.resolution);
183 }
184 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000185 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700186}
187
188void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700189 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800190 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700191 dumpParameters(dump);
192 dumpVirtualKeys(dump);
193 dumpRawPointerAxes(dump);
194 dumpCalibration(dump);
195 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700196 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700197
198 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700199 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
200 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
201 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
202 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
203 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
204 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
205 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
206 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
207 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
208 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
209 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
210 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
211 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
212 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
213
214 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
215 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
216 mLastRawState.rawPointerData.pointerCount);
217 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
218 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
219 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
220 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
221 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
222 "toolType=%d, isHovering=%s\n",
223 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
224 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
225 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
226 pointer.distance, pointer.toolType, toString(pointer.isHovering));
227 }
228
229 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
230 mLastCookedState.buttonState);
231 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
232 mLastCookedState.cookedPointerData.pointerCount);
233 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
234 const PointerProperties& pointerProperties =
235 mLastCookedState.cookedPointerData.pointerProperties[i];
236 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000237 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
238 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
239 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700240 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
241 "toolType=%d, isHovering=%s\n",
242 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000243 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
244 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700245 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
246 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
247 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
248 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
249 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
250 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
251 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
252 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
253 pointerProperties.toolType,
254 toString(mLastCookedState.cookedPointerData.isHovering(i)));
255 }
256
257 dump += INDENT3 "Stylus Fusion:\n";
258 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
259 toString(mExternalStylusConnected));
260 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
261 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
262 mExternalStylusFusionTimeout);
263 dump += INDENT3 "External Stylus State:\n";
264 dumpStylusState(dump, mExternalStylusState);
265
Michael Wright227c5542020-07-02 18:30:52 +0100266 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700267 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
268 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
269 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
270 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
271 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
272 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
273 }
274}
275
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700276std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
277 const InputReaderConfiguration* config,
278 uint32_t changes) {
279 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700280
281 mConfig = *config;
282
283 if (!changes) { // first time only
284 // Configure basic parameters.
285 configureParameters();
286
287 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800288 mCursorScrollAccumulator.configure(getDeviceContext());
289 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700290
291 // Configure absolute axis information.
292 configureRawPointerAxes();
293
294 // Prepare input device calibration.
295 parseCalibration();
296 resolveCalibration();
297 }
298
299 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
300 // Update location calibration to reflect current settings
301 updateAffineTransformation();
302 }
303
304 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
305 // Update pointer speed.
306 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
307 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
308 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
309 }
310
311 bool resetNeeded = false;
312 if (!changes ||
313 (changes &
314 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800315 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700316 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
317 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
318 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700319 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700320 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700321 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700322 }
323
324 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700325 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000326
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700327 // Send reset, unless this is the first time the device has been configured,
328 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000329 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700330 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700331 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700332}
333
334void TouchInputMapper::resolveExternalStylusPresence() {
335 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800336 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 mExternalStylusConnected = !devices.empty();
338
339 if (!mExternalStylusConnected) {
340 resetExternalStylus();
341 }
342}
343
344void TouchInputMapper::configureParameters() {
345 // Use the pointer presentation mode for devices that do not support distinct
346 // multitouch. The spot-based presentation relies on being able to accurately
347 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800348 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100349 ? Parameters::GestureMode::SINGLE_TOUCH
350 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700352 std::string gestureModeString;
353 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800354 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100356 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700357 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100358 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700359 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700360 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700361 }
362 }
363
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800364 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700365 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100366 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800367 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700368 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100369 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700370 } else {
371 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100372 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700373 }
374
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800375 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700376
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700377 std::string deviceTypeString;
378 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800379 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700380 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100381 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700382 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100383 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100385 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700386 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700387 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700388 }
389 }
390
Michael Wright227c5542020-07-02 18:30:52 +0100391 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700392 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800393 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700394
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700395 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700396 std::string orientationString;
397 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700398 orientationString)) {
399 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
400 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
401 } else if (orientationString == "ORIENTATION_90") {
402 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
403 } else if (orientationString == "ORIENTATION_180") {
404 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
405 } else if (orientationString == "ORIENTATION_270") {
406 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
407 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700408 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700409 }
410 }
411
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700412 mParameters.hasAssociatedDisplay = false;
413 mParameters.associatedDisplayIsExternal = false;
414 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100415 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
416 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700417 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100418 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700420 std::string uniqueDisplayId;
421 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800422 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
424 }
425 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800426 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700427 mParameters.hasAssociatedDisplay = true;
428 }
429
430 // Initial downs on external touch devices should wake the device.
431 // Normally we don't do this for internal touch screens to prevent them from waking
432 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800433 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700434 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000435
436 mParameters.supportsUsi = false;
437 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
438 mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439}
440
441void TouchInputMapper::dumpParameters(std::string& dump) {
442 dump += INDENT3 "Parameters:\n";
443
Dominik Laskowski75788452021-02-09 18:51:25 -0800444 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700445
Dominik Laskowski75788452021-02-09 18:51:25 -0800446 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447
448 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
449 "displayId='%s'\n",
450 toString(mParameters.hasAssociatedDisplay),
451 toString(mParameters.associatedDisplayIsExternal),
452 mParameters.uniqueDisplayId.c_str());
453 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800454 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000455 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456}
457
458void TouchInputMapper::configureRawPointerAxes() {
459 mRawPointerAxes.clear();
460}
461
462void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
463 dump += INDENT3 "Raw Touch Axes:\n";
464 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
465 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
466 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
467 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
468 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
469 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
470 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
471 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
472 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
473 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
474 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
475 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
476 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
477}
478
479bool TouchInputMapper::hasExternalStylus() const {
480 return mExternalStylusConnected;
481}
482
483/**
484 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000485 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800486 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000487 * 3. Get the matching viewport by either unique id in idc file or by the display type
488 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800489 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700490 */
491std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800492 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000493 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700495 }
496
Christine Franks2a2293c2022-01-18 11:51:16 -0800497 const std::optional<std::string> associatedDisplayUniqueId =
498 getDeviceContext().getAssociatedDisplayUniqueId();
499 if (associatedDisplayUniqueId) {
500 return getDeviceContext().getAssociatedViewport();
501 }
502
Michael Wright227c5542020-07-02 18:30:52 +0100503 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800504 std::optional<DisplayViewport> viewport =
505 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
506 if (viewport) {
507 return viewport;
508 } else {
509 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
510 mConfig.defaultPointerDisplayId);
511 }
512 }
513
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514 // Check if uniqueDisplayId is specified in idc file.
515 if (!mParameters.uniqueDisplayId.empty()) {
516 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
517 }
518
519 ViewportType viewportTypeToUse;
520 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100521 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700522 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100523 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700524 }
525
526 std::optional<DisplayViewport> viewport =
527 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100528 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700529 ALOGW("Input device %s should be associated with external display, "
530 "fallback to internal one for the external viewport is not found.",
531 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100532 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700533 }
534
535 return viewport;
536 }
537
538 // No associated display, return a non-display viewport.
539 DisplayViewport newViewport;
540 // Raw width and height in the natural orientation.
541 int32_t rawWidth = mRawPointerAxes.getRawWidth();
542 int32_t rawHeight = mRawPointerAxes.getRawHeight();
543 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
544 return std::make_optional(newViewport);
545}
546
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800547int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
548 if (resolution < 0) {
549 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
550 getDeviceName().c_str());
551 return 0;
552 }
553 return resolution;
554}
555
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800556void TouchInputMapper::initializeSizeRanges() {
557 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
558 mSizeScale = 0.0f;
559 return;
560 }
561
562 // Size of diagonal axis.
563 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
564
565 // Size factors.
566 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
567 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
568 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
569 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
570 } else {
571 mSizeScale = 0.0f;
572 }
573
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700574 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
575 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
576 .source = mSource,
577 .min = 0,
578 .max = diagonalSize,
579 .flat = 0,
580 .fuzz = 0,
581 .resolution = 0,
582 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800583
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800584 if (mRawPointerAxes.touchMajor.valid) {
585 mRawPointerAxes.touchMajor.resolution =
586 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700587 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800588 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800589
590 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700591 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800592 if (mRawPointerAxes.touchMinor.valid) {
593 mRawPointerAxes.touchMinor.resolution =
594 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700595 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800596 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800597
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700598 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
599 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
600 .source = mSource,
601 .min = 0,
602 .max = diagonalSize,
603 .flat = 0,
604 .fuzz = 0,
605 .resolution = 0,
606 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800607 if (mRawPointerAxes.toolMajor.valid) {
608 mRawPointerAxes.toolMajor.resolution =
609 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700610 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800611 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800612
613 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700614 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800615 if (mRawPointerAxes.toolMinor.valid) {
616 mRawPointerAxes.toolMinor.resolution =
617 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700618 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800619 }
620
621 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700622 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
623 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
624 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
625 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800626 } else {
627 // Support for other calibrations can be added here.
628 ALOGW("%s calibration is not supported for size ranges at the moment. "
629 "Using raw resolution instead",
630 ftl::enum_string(mCalibration.sizeCalibration).c_str());
631 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800632
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700633 mOrientedRanges.size = InputDeviceInfo::MotionRange{
634 .axis = AMOTION_EVENT_AXIS_SIZE,
635 .source = mSource,
636 .min = 0,
637 .max = 1.0,
638 .flat = 0,
639 .fuzz = 0,
640 .resolution = 0,
641 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800642}
643
644void TouchInputMapper::initializeOrientedRanges() {
645 // Configure X and Y factors.
646 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
647 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
648 mXPrecision = 1.0f / mXScale;
649 mYPrecision = 1.0f / mYScale;
650
651 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
652 mOrientedRanges.x.source = mSource;
653 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
654 mOrientedRanges.y.source = mSource;
655
656 // Scale factor for terms that are not oriented in a particular axis.
657 // If the pixels are square then xScale == yScale otherwise we fake it
658 // by choosing an average.
659 mGeometricScale = avg(mXScale, mYScale);
660
661 initializeSizeRanges();
662
663 // Pressure factors.
664 mPressureScale = 0;
665 float pressureMax = 1.0;
666 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
667 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700668 if (mCalibration.pressureScale) {
669 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800670 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
671 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
672 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
673 }
674 }
675
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700676 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
677 .axis = AMOTION_EVENT_AXIS_PRESSURE,
678 .source = mSource,
679 .min = 0,
680 .max = pressureMax,
681 .flat = 0,
682 .fuzz = 0,
683 .resolution = 0,
684 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800685
686 // Tilt
687 mTiltXCenter = 0;
688 mTiltXScale = 0;
689 mTiltYCenter = 0;
690 mTiltYScale = 0;
691 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
692 if (mHaveTilt) {
693 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
694 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
695 mTiltXScale = M_PI / 180;
696 mTiltYScale = M_PI / 180;
697
698 if (mRawPointerAxes.tiltX.resolution) {
699 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
700 }
701 if (mRawPointerAxes.tiltY.resolution) {
702 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
703 }
704
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700705 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
706 .axis = AMOTION_EVENT_AXIS_TILT,
707 .source = mSource,
708 .min = 0,
709 .max = M_PI_2,
710 .flat = 0,
711 .fuzz = 0,
712 .resolution = 0,
713 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800714 }
715
716 // Orientation
717 mOrientationScale = 0;
718 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700719 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
720 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
721 .source = mSource,
722 .min = -M_PI,
723 .max = M_PI,
724 .flat = 0,
725 .fuzz = 0,
726 .resolution = 0,
727 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800728
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800729 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
730 if (mCalibration.orientationCalibration ==
731 Calibration::OrientationCalibration::INTERPOLATED) {
732 if (mRawPointerAxes.orientation.valid) {
733 if (mRawPointerAxes.orientation.maxValue > 0) {
734 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
735 } else if (mRawPointerAxes.orientation.minValue < 0) {
736 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
737 } else {
738 mOrientationScale = 0;
739 }
740 }
741 }
742
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700743 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
744 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
745 .source = mSource,
746 .min = -M_PI_2,
747 .max = M_PI_2,
748 .flat = 0,
749 .fuzz = 0,
750 .resolution = 0,
751 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800752 }
753
754 // Distance
755 mDistanceScale = 0;
756 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
757 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700758 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800759 }
760
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700761 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800762
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700763 .axis = AMOTION_EVENT_AXIS_DISTANCE,
764 .source = mSource,
765 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
766 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
767 .flat = 0,
768 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
769 .resolution = 0,
770 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800771 }
772
773 // Compute oriented precision, scales and ranges.
774 // Note that the maximum value reported is an inclusive maximum value so it is one
775 // unit less than the total width or height of the display.
776 switch (mInputDeviceOrientation) {
777 case DISPLAY_ORIENTATION_90:
778 case DISPLAY_ORIENTATION_270:
779 mOrientedXPrecision = mYPrecision;
780 mOrientedYPrecision = mXPrecision;
781
782 mOrientedRanges.x.min = 0;
783 mOrientedRanges.x.max = mDisplayHeight - 1;
784 mOrientedRanges.x.flat = 0;
785 mOrientedRanges.x.fuzz = 0;
786 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
787
788 mOrientedRanges.y.min = 0;
789 mOrientedRanges.y.max = mDisplayWidth - 1;
790 mOrientedRanges.y.flat = 0;
791 mOrientedRanges.y.fuzz = 0;
792 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
793 break;
794
795 default:
796 mOrientedXPrecision = mXPrecision;
797 mOrientedYPrecision = mYPrecision;
798
799 mOrientedRanges.x.min = 0;
800 mOrientedRanges.x.max = mDisplayWidth - 1;
801 mOrientedRanges.x.flat = 0;
802 mOrientedRanges.x.fuzz = 0;
803 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
804
805 mOrientedRanges.y.min = 0;
806 mOrientedRanges.y.max = mDisplayHeight - 1;
807 mOrientedRanges.y.flat = 0;
808 mOrientedRanges.y.fuzz = 0;
809 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
810 break;
811 }
812}
813
Prabir Pradhan1728b212021-10-19 16:00:03 -0700814void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000815 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700816
817 resolveExternalStylusPresence();
818
819 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100820 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000821 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700822 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100823 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700824 if (hasStylus()) {
825 mSource |= AINPUT_SOURCE_STYLUS;
826 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800827 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700828 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100829 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700830 if (hasStylus()) {
831 mSource |= AINPUT_SOURCE_STYLUS;
832 }
833 if (hasExternalStylus()) {
834 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
835 }
Michael Wright227c5542020-07-02 18:30:52 +0100836 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700837 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100838 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700839 } else {
840 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100841 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700842 }
843
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000844 const std::optional<DisplayViewport> newViewportOpt = findViewport();
845
846 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700847 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
848 ALOGW("Touch device '%s' did not report support for X or Y axis! "
849 "The device will be inoperable.",
850 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100851 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000852 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700853 ALOGI("Touch device '%s' could not query the properties of its associated "
854 "display. The device will be inoperable until the display size "
855 "becomes available.",
856 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100857 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000858 } else if (!newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000859 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
860 getDeviceName().c_str(), getDeviceId());
861 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000862 }
863
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700864 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700865 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
866 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000867 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
868 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
869 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
870 const float rawMeanResolution =
871 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700872
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000873 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
874 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700875 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700876 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000877 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
878 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
879 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700880
Michael Wright227c5542020-07-02 18:30:52 +0100881 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700882 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700883 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
884 int32_t naturalPhysicalLeft, naturalPhysicalTop;
885 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700886
Prabir Pradhan1728b212021-10-19 16:00:03 -0700887 // Apply the inverse of the input device orientation so that the input device is
888 // configured in the same orientation as the viewport. The input device orientation will
889 // be re-applied by mInputDeviceOrientation.
890 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700891 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700892 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700893 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700894 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
895 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800896 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700897 naturalPhysicalTop = mViewport.physicalLeft;
898 naturalDeviceWidth = mViewport.deviceHeight;
899 naturalDeviceHeight = mViewport.deviceWidth;
900 break;
901 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
903 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
904 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
905 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
906 naturalDeviceWidth = mViewport.deviceWidth;
907 naturalDeviceHeight = mViewport.deviceHeight;
908 break;
909 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700910 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
911 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
912 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800913 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700914 naturalDeviceWidth = mViewport.deviceHeight;
915 naturalDeviceHeight = mViewport.deviceWidth;
916 break;
917 case DISPLAY_ORIENTATION_0:
918 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700919 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
920 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
921 naturalPhysicalLeft = mViewport.physicalLeft;
922 naturalPhysicalTop = mViewport.physicalTop;
923 naturalDeviceWidth = mViewport.deviceWidth;
924 naturalDeviceHeight = mViewport.deviceHeight;
925 break;
926 }
927
928 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
929 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
930 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
931 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
932 }
933
934 mPhysicalWidth = naturalPhysicalWidth;
935 mPhysicalHeight = naturalPhysicalHeight;
936 mPhysicalLeft = naturalPhysicalLeft;
937 mPhysicalTop = naturalPhysicalTop;
938
Prabir Pradhan1728b212021-10-19 16:00:03 -0700939 const int32_t oldDisplayWidth = mDisplayWidth;
940 const int32_t oldDisplayHeight = mDisplayHeight;
941 mDisplayWidth = naturalDeviceWidth;
942 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700943
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000944 // InputReader works in the un-rotated display coordinate space, so we don't need to do
945 // anything if the device is already orientation-aware. If the device is not
946 // orientation-aware, then we need to apply the inverse rotation of the display so that
947 // when the display rotation is applied later as a part of the per-window transform, we
948 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700949 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000950 ? DISPLAY_ORIENTATION_0
951 : getInverseRotation(mViewport.orientation);
952 // For orientation-aware devices that work in the un-rotated coordinate space, the
953 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000954 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
955 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
956 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700957
958 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700959 mInputDeviceOrientation =
960 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700961 } else {
962 mPhysicalWidth = rawWidth;
963 mPhysicalHeight = rawHeight;
964 mPhysicalLeft = 0;
965 mPhysicalTop = 0;
966
Prabir Pradhan1728b212021-10-19 16:00:03 -0700967 mDisplayWidth = rawWidth;
968 mDisplayHeight = rawHeight;
969 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700970 }
971 }
972
973 // If moving between pointer modes, need to reset some state.
974 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
975 if (deviceModeChanged) {
976 mOrientedRanges.clear();
977 }
978
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800979 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
980 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100981 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800982 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000983 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
984 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800985 if (mPointerController == nullptr) {
986 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700987 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000988 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800989 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
990 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700991 } else {
lilinnandef700b2022-06-17 19:32:01 +0800992 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
993 !mConfig.showTouches) {
994 mPointerController->clearSpots();
995 }
Michael Wright17db18e2020-06-26 20:51:44 +0100996 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700997 }
998
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700999 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001000 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1001 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001002 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1003 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001005 configureVirtualKeys();
1006
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001007 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008
1009 // Location
1010 updateAffineTransformation();
1011
Michael Wright227c5542020-07-02 18:30:52 +01001012 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001013 // Compute pointer gesture detection parameters.
1014 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001015 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001016
1017 // Scale movements such that one whole swipe of the touch pad covers a
1018 // given area relative to the diagonal size of the display when no acceleration
1019 // is applied.
1020 // Assume that the touch pad has a square aspect ratio such that movements in
1021 // X and Y of the same number of raw units cover the same physical distance.
1022 mPointerXMovementScale =
1023 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1024 mPointerYMovementScale = mPointerXMovementScale;
1025
1026 // Scale zooms to cover a smaller range of the display than movements do.
1027 // This value determines the area around the pointer that is affected by freeform
1028 // pointer gestures.
1029 mPointerXZoomScale =
1030 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1031 mPointerYZoomScale = mPointerXZoomScale;
1032
HQ Liue6983c72022-04-19 22:14:56 +00001033 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1034 // axis is non positive value.
1035 const float minFreeformGestureWidth =
1036 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1037
1038 mPointerGestureMaxSwipeWidth =
1039 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1040 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001041 }
1042
1043 // Inform the dispatcher about the changes.
1044 *outResetNeeded = true;
1045 bumpGeneration();
1046 }
1047}
1048
Prabir Pradhan1728b212021-10-19 16:00:03 -07001049void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001050 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001051 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1052 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1054 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1055 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1056 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001057 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001058}
1059
1060void TouchInputMapper::configureVirtualKeys() {
1061 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001062 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001063
1064 mVirtualKeys.clear();
1065
1066 if (virtualKeyDefinitions.size() == 0) {
1067 return;
1068 }
1069
1070 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1071 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1072 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1073 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1074
1075 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1076 VirtualKey virtualKey;
1077
1078 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1079 int32_t keyCode;
1080 int32_t dummyKeyMetaState;
1081 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001082 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1083 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001084 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1085 continue; // drop the key
1086 }
1087
1088 virtualKey.keyCode = keyCode;
1089 virtualKey.flags = flags;
1090
1091 // convert the key definition's display coordinates into touch coordinates for a hit box
1092 int32_t halfWidth = virtualKeyDefinition.width / 2;
1093 int32_t halfHeight = virtualKeyDefinition.height / 2;
1094
1095 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001096 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001097 touchScreenLeft;
1098 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001099 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001100 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001101 virtualKey.hitTop =
1102 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001103 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001104 virtualKey.hitBottom =
1105 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001106 touchScreenTop;
1107 mVirtualKeys.push_back(virtualKey);
1108 }
1109}
1110
1111void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1112 if (!mVirtualKeys.empty()) {
1113 dump += INDENT3 "Virtual Keys:\n";
1114
1115 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1116 const VirtualKey& virtualKey = mVirtualKeys[i];
1117 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1118 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1119 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1120 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1121 }
1122 }
1123}
1124
1125void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001126 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001127 Calibration& out = mCalibration;
1128
1129 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001130 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001131 std::string sizeCalibrationString;
1132 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001134 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001144 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 }
1146 }
1147
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001148 float sizeScale;
1149
1150 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1151 out.sizeScale = sizeScale;
1152 }
1153 float sizeBias;
1154 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1155 out.sizeBias = sizeBias;
1156 }
1157 bool sizeIsSummed;
1158 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1159 out.sizeIsSummed = sizeIsSummed;
1160 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001161
1162 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001164 std::string pressureCalibrationString;
1165 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (pressureCalibrationString != "default") {
1173 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001174 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 }
1176 }
1177
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001178 float pressureScale;
1179 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1180 out.pressureScale = pressureScale;
1181 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182
1183 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001185 std::string orientationCalibrationString;
1186 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001187 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 } else if (orientationCalibrationString != "default") {
1194 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001195 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 }
1197 }
1198
1199 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001201 std::string distanceCalibrationString;
1202 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 } else if (distanceCalibrationString != "default") {
1208 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001209 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 }
1211 }
1212
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001213 float distanceScale;
1214 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1215 out.distanceScale = distanceScale;
1216 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001219 std::string coverageCalibrationString;
1220 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 } else if (coverageCalibrationString != "default") {
1226 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001227 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229 }
1230}
1231
1232void TouchInputMapper::resolveCalibration() {
1233 // Size
1234 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001235 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1236 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001239 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 }
1241
1242 // Pressure
1243 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001244 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1245 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001248 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250
1251 // Orientation
1252 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001253 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1254 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001257 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
1259
1260 // Distance
1261 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001262 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1263 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001266 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 }
1268
1269 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001270 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1271 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 }
1273}
1274
1275void TouchInputMapper::dumpCalibration(std::string& dump) {
1276 dump += INDENT3 "Calibration:\n";
1277
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001278 dump += INDENT4 "touch.size.calibration: ";
1279 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001281 if (mCalibration.sizeScale) {
1282 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 }
1284
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001285 if (mCalibration.sizeBias) {
1286 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 }
1288
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001289 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001291 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 }
1293
1294 // Pressure
1295 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001296 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 dump += INDENT4 "touch.pressure.calibration: none\n";
1298 break;
Michael Wright227c5542020-07-02 18:30:52 +01001299 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 dump += INDENT4 "touch.pressure.calibration: physical\n";
1301 break;
Michael Wright227c5542020-07-02 18:30:52 +01001302 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1304 break;
1305 default:
1306 ALOG_ASSERT(false);
1307 }
1308
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001309 if (mCalibration.pressureScale) {
1310 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 }
1312
1313 // Orientation
1314 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.orientation.calibration: none\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1320 break;
Michael Wright227c5542020-07-02 18:30:52 +01001321 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += INDENT4 "touch.orientation.calibration: vector\n";
1323 break;
1324 default:
1325 ALOG_ASSERT(false);
1326 }
1327
1328 // Distance
1329 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.distance.calibration: none\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.distance.calibration: scaled\n";
1335 break;
1336 default:
1337 ALOG_ASSERT(false);
1338 }
1339
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001340 if (mCalibration.distanceScale) {
1341 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001342 }
1343
1344 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001345 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 dump += INDENT4 "touch.coverage.calibration: none\n";
1347 break;
Michael Wright227c5542020-07-02 18:30:52 +01001348 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349 dump += INDENT4 "touch.coverage.calibration: box\n";
1350 break;
1351 default:
1352 ALOG_ASSERT(false);
1353 }
1354}
1355
1356void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1357 dump += INDENT3 "Affine Transformation:\n";
1358
1359 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1360 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1361 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1362 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1363 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1364 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1365}
1366
1367void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001368 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001369 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001370}
1371
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001372std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001373 std::list<NotifyArgs> out = cancelTouch(when, when);
1374 updateTouchSpots();
1375
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001376 mCursorButtonAccumulator.reset(getDeviceContext());
1377 mCursorScrollAccumulator.reset(getDeviceContext());
1378 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379
1380 mPointerVelocityControl.reset();
1381 mWheelXVelocityControl.reset();
1382 mWheelYVelocityControl.reset();
1383
1384 mRawStatesPending.clear();
1385 mCurrentRawState.clear();
1386 mCurrentCookedState.clear();
1387 mLastRawState.clear();
1388 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001389 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001390 mSentHoverEnter = false;
1391 mHavePointerIds = false;
1392 mCurrentMotionAborted = false;
1393 mDownTime = 0;
1394
1395 mCurrentVirtualKey.down = false;
1396
1397 mPointerGesture.reset();
1398 mPointerSimple.reset();
1399 resetExternalStylus();
1400
1401 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001402 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001403 mPointerController->clearSpots();
1404 }
1405
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001406 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407}
1408
1409void TouchInputMapper::resetExternalStylus() {
1410 mExternalStylusState.clear();
1411 mExternalStylusId = -1;
1412 mExternalStylusFusionTimeout = LLONG_MAX;
1413 mExternalStylusDataPending = false;
1414}
1415
1416void TouchInputMapper::clearStylusDataPendingFlags() {
1417 mExternalStylusDataPending = false;
1418 mExternalStylusFusionTimeout = LLONG_MAX;
1419}
1420
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001421std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422 mCursorButtonAccumulator.process(rawEvent);
1423 mCursorScrollAccumulator.process(rawEvent);
1424 mTouchButtonAccumulator.process(rawEvent);
1425
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001426 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001428 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001429 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001430 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431}
1432
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001433std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1434 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001435 if (mDeviceMode == DeviceMode::DISABLED) {
1436 // Only save the last pending state when the device is disabled.
1437 mRawStatesPending.clear();
1438 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439 // Push a new state.
1440 mRawStatesPending.emplace_back();
1441
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001442 RawState& next = mRawStatesPending.back();
1443 next.clear();
1444 next.when = when;
1445 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446
1447 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001448 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001449 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1450
1451 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001452 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1453 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001454 mCursorScrollAccumulator.finishSync();
1455
1456 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001457 syncTouch(when, &next);
1458
1459 // The last RawState is the actually second to last, since we just added a new state
1460 const RawState& last =
1461 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001462
1463 // Assign pointer ids.
1464 if (!mHavePointerIds) {
1465 assignPointerIds(last, next);
1466 }
1467
Harry Cutts45483602022-08-24 14:36:48 +00001468 ALOGD_IF(DEBUG_RAW_EVENTS,
1469 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1470 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1471 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1472 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1473 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1474 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001475
Arthur Hung9ad18942021-06-19 02:04:46 +00001476 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1477 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1478 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1479 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1480 next.rawPointerData.hoveringIdBits.value);
1481 }
1482
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001483 out += processRawTouches(false /*timeout*/);
1484 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485}
1486
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001487std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1488 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001489 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001490 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001491 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001492 }
1493
1494 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1495 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1496 // touching the current state will only observe the events that have been dispatched to the
1497 // rest of the pipeline.
1498 const size_t N = mRawStatesPending.size();
1499 size_t count;
1500 for (count = 0; count < N; count++) {
1501 const RawState& next = mRawStatesPending[count];
1502
1503 // A failure to assign the stylus id means that we're waiting on stylus data
1504 // and so should defer the rest of the pipeline.
1505 if (assignExternalStylusId(next, timeout)) {
1506 break;
1507 }
1508
1509 // All ready to go.
1510 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001511 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001512 if (mCurrentRawState.when < mLastRawState.when) {
1513 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001514 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001515 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001516 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 }
1518 if (count != 0) {
1519 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1520 }
1521
1522 if (mExternalStylusDataPending) {
1523 if (timeout) {
1524 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1525 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001526 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001527 ALOGD_IF(DEBUG_STYLUS_FUSION,
1528 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001529 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001530 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001531 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1532 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1533 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1534 }
1535 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001536 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001537}
1538
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001539std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1540 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001541 // Always start with a clean state.
1542 mCurrentCookedState.clear();
1543
1544 // Apply stylus buttons to current raw state.
1545 applyExternalStylusButtonState(when);
1546
1547 // Handle policy on initial down or hover events.
1548 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1549 mCurrentRawState.rawPointerData.pointerCount != 0;
1550
1551 uint32_t policyFlags = 0;
1552 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1553 if (initialDown || buttonsPressed) {
1554 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001555 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001556 getContext()->fadePointer();
1557 }
1558
1559 if (mParameters.wake) {
1560 policyFlags |= POLICY_FLAG_WAKE;
1561 }
1562 }
1563
1564 // Consume raw off-screen touches before cooking pointer data.
1565 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001566 bool consumed;
1567 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1568 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001569 mCurrentRawState.rawPointerData.clear();
1570 }
1571
1572 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1573 // with cooked pointer data that has the same ids and indices as the raw data.
1574 // The following code can use either the raw or cooked data, as needed.
1575 cookPointerData();
1576
1577 // Apply stylus pressure to current cooked state.
1578 applyExternalStylusTouchState(when);
1579
1580 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001581 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1582 mSource, mViewport.displayId, policyFlags,
1583 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001584
1585 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001586 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001587 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1588 uint32_t id = idBits.clearFirstMarkedBit();
1589 const RawPointerData::Pointer& pointer =
1590 mCurrentRawState.rawPointerData.pointerForId(id);
1591 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1592 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1593 mCurrentCookedState.stylusIdBits.markBit(id);
1594 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1595 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1596 mCurrentCookedState.fingerIdBits.markBit(id);
1597 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1598 mCurrentCookedState.mouseIdBits.markBit(id);
1599 }
1600 }
1601 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1602 uint32_t id = idBits.clearFirstMarkedBit();
1603 const RawPointerData::Pointer& pointer =
1604 mCurrentRawState.rawPointerData.pointerForId(id);
1605 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1606 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1607 mCurrentCookedState.stylusIdBits.markBit(id);
1608 }
1609 }
1610
1611 // Stylus takes precedence over all tools, then mouse, then finger.
1612 PointerUsage pointerUsage = mPointerUsage;
1613 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1614 mCurrentCookedState.mouseIdBits.clear();
1615 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001616 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1618 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001619 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1621 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001622 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001623 }
1624
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001625 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001628 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001629 out += dispatchButtonRelease(when, readTime, policyFlags);
1630 out += dispatchHoverExit(when, readTime, policyFlags);
1631 out += dispatchTouches(when, readTime, policyFlags);
1632 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1633 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634 }
1635
1636 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1637 mCurrentMotionAborted = false;
1638 }
1639 }
1640
1641 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001642 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1643 mSource, mViewport.displayId, policyFlags,
1644 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001645
1646 // Clear some transient state.
1647 mCurrentRawState.rawVScroll = 0;
1648 mCurrentRawState.rawHScroll = 0;
1649
1650 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001651 mLastRawState = mCurrentRawState;
1652 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001653 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001654}
1655
Garfield Tanc734e4f2021-01-15 20:01:39 -08001656void TouchInputMapper::updateTouchSpots() {
1657 if (!mConfig.showTouches || mPointerController == nullptr) {
1658 return;
1659 }
1660
1661 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1662 // clear touch spots.
1663 if (mDeviceMode != DeviceMode::DIRECT &&
1664 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1665 return;
1666 }
1667
1668 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1669 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1670
1671 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001672 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1673 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001674 mCurrentCookedState.cookedPointerData.touchingIdBits,
1675 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001676}
1677
1678bool TouchInputMapper::isTouchScreen() {
1679 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1680 mParameters.hasAssociatedDisplay;
1681}
1682
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001683void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001684 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001685 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1686 }
1687}
1688
1689void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1690 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1691 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1692
1693 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1694 float pressure = mExternalStylusState.pressure;
1695 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1696 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1697 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1698 }
1699 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1700 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1701
1702 PointerProperties& properties =
1703 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1704 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1705 properties.toolType = mExternalStylusState.toolType;
1706 }
1707 }
1708}
1709
1710bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001711 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001712 return false;
1713 }
1714
1715 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1716 state.rawPointerData.pointerCount != 0;
1717 if (initialDown) {
1718 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001719 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001720 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1721 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001722 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001723 resetExternalStylus();
1724 } else {
1725 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1726 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1727 }
Harry Cutts45483602022-08-24 14:36:48 +00001728 ALOGD_IF(DEBUG_STYLUS_FUSION,
1729 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1730 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001731 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1732 return true;
1733 }
1734 }
1735
1736 // Check if the stylus pointer has gone up.
1737 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001738 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001739 mExternalStylusId = -1;
1740 }
1741
1742 return false;
1743}
1744
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001745std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1746 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001747 if (mDeviceMode == DeviceMode::POINTER) {
1748 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001749 // Since this is a synthetic event, we can consider its latency to be zero
1750 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001751 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001752 }
Michael Wright227c5542020-07-02 18:30:52 +01001753 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001754 if (mExternalStylusFusionTimeout < when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001755 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001756 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1757 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1758 }
1759 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001760 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001761}
1762
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001763std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1764 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001765 mExternalStylusState.copyFrom(state);
1766 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1767 // We're either in the middle of a fused stream of data or we're waiting on data before
1768 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1769 // data.
1770 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001771 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001772 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001773 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001774}
1775
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001776std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1777 uint32_t policyFlags, bool& outConsumed) {
1778 outConsumed = false;
1779 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780 // Check for release of a virtual key.
1781 if (mCurrentVirtualKey.down) {
1782 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1783 // Pointer went up while virtual key was down.
1784 mCurrentVirtualKey.down = false;
1785 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001786 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1787 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1788 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001789 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1790 AKEY_EVENT_FLAG_FROM_SYSTEM |
1791 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001793 outConsumed = true;
1794 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001795 }
1796
1797 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1798 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1799 const RawPointerData::Pointer& pointer =
1800 mCurrentRawState.rawPointerData.pointerForId(id);
1801 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1802 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1803 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001804 outConsumed = true;
1805 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001806 }
1807 }
1808
1809 // Pointer left virtual key area or another pointer also went down.
1810 // Send key cancellation but do not consume the touch yet.
1811 // This is useful when the user swipes through from the virtual key area
1812 // into the main display surface.
1813 mCurrentVirtualKey.down = false;
1814 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001815 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1816 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001817 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1818 AKEY_EVENT_FLAG_FROM_SYSTEM |
1819 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1820 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001821 }
1822 }
1823
1824 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1825 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1826 // Pointer just went down. Check for virtual key press or off-screen touches.
1827 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1828 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001829 // Skip checking whether the pointer is inside the physical frame if the device is in
1830 // unscaled mode.
1831 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1832 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001833 // If exactly one pointer went down, check for virtual key hit.
1834 // Otherwise we will drop the entire stroke.
1835 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1836 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1837 if (virtualKey) {
1838 mCurrentVirtualKey.down = true;
1839 mCurrentVirtualKey.downTime = when;
1840 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1841 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1842 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001843 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1844 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001845
1846 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001847 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1848 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1849 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001850 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1851 AKEY_EVENT_ACTION_DOWN,
1852 AKEY_EVENT_FLAG_FROM_SYSTEM |
1853 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854 }
1855 }
1856 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001857 outConsumed = true;
1858 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001859 }
1860 }
1861
1862 // Disable all virtual key touches that happen within a short time interval of the
1863 // most recent touch within the screen area. The idea is to filter out stray
1864 // virtual key presses when interacting with the touch screen.
1865 //
1866 // Problems we're trying to solve:
1867 //
1868 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1869 // virtual key area that is implemented by a separate touch panel and accidentally
1870 // triggers a virtual key.
1871 //
1872 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1873 // area and accidentally triggers a virtual key. This often happens when virtual keys
1874 // are layed out below the screen near to where the on screen keyboard's space bar
1875 // is displayed.
1876 if (mConfig.virtualKeyQuietTime > 0 &&
1877 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001878 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001879 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001880 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001881}
1882
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001883NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1884 uint32_t policyFlags, int32_t keyEventAction,
1885 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001886 int32_t keyCode = mCurrentVirtualKey.keyCode;
1887 int32_t scanCode = mCurrentVirtualKey.scanCode;
1888 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001889 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001890 policyFlags |= POLICY_FLAG_VIRTUAL;
1891
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001892 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1893 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1894 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001895}
1896
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001897std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1898 uint32_t policyFlags) {
1899 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001900 if (mCurrentMotionAborted) {
1901 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001902 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001903 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001904 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1905 if (!currentIdBits.isEmpty()) {
1906 int32_t metaState = getContext()->getGlobalMetaState();
1907 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001908 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001909 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1910 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001911 mCurrentCookedState.cookedPointerData.pointerProperties,
1912 mCurrentCookedState.cookedPointerData.pointerCoords,
1913 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1914 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1915 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001916 mCurrentMotionAborted = true;
1917 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001918 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001919}
1920
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001921// Updates pointer coords and properties for pointers with specified ids that have moved.
1922// Returns true if any of them changed.
1923static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1924 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1925 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1926 BitSet32 idBits) {
1927 bool changed = false;
1928 while (!idBits.isEmpty()) {
1929 uint32_t id = idBits.clearFirstMarkedBit();
1930 uint32_t inIndex = inIdToIndex[id];
1931 uint32_t outIndex = outIdToIndex[id];
1932
1933 const PointerProperties& curInProperties = inProperties[inIndex];
1934 const PointerCoords& curInCoords = inCoords[inIndex];
1935 PointerProperties& curOutProperties = outProperties[outIndex];
1936 PointerCoords& curOutCoords = outCoords[outIndex];
1937
1938 if (curInProperties != curOutProperties) {
1939 curOutProperties.copyFrom(curInProperties);
1940 changed = true;
1941 }
1942
1943 if (curInCoords != curOutCoords) {
1944 curOutCoords.copyFrom(curInCoords);
1945 changed = true;
1946 }
1947 }
1948 return changed;
1949}
1950
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001951std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1952 uint32_t policyFlags) {
1953 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001954 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1955 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1956 int32_t metaState = getContext()->getGlobalMetaState();
1957 int32_t buttonState = mCurrentCookedState.buttonState;
1958
1959 if (currentIdBits == lastIdBits) {
1960 if (!currentIdBits.isEmpty()) {
1961 // No pointer id changes so this is a move event.
1962 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001963 out.push_back(
1964 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1965 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1966 mCurrentCookedState.cookedPointerData.pointerProperties,
1967 mCurrentCookedState.cookedPointerData.pointerCoords,
1968 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1969 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1970 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001971 }
1972 } else {
1973 // There may be pointers going up and pointers going down and pointers moving
1974 // all at the same time.
1975 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1976 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1977 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1978 BitSet32 dispatchedIdBits(lastIdBits.value);
1979
1980 // Update last coordinates of pointers that have moved so that we observe the new
1981 // pointer positions at the same time as other pointers that have just gone up.
1982 bool moveNeeded =
1983 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1984 mCurrentCookedState.cookedPointerData.pointerCoords,
1985 mCurrentCookedState.cookedPointerData.idToIndex,
1986 mLastCookedState.cookedPointerData.pointerProperties,
1987 mLastCookedState.cookedPointerData.pointerCoords,
1988 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1989 if (buttonState != mLastCookedState.buttonState) {
1990 moveNeeded = true;
1991 }
1992
1993 // Dispatch pointer up events.
1994 while (!upIdBits.isEmpty()) {
1995 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001996 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001997 if (isCanceled) {
1998 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1999 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002000 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2001 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2002 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2003 buttonState, 0,
2004 mLastCookedState.cookedPointerData.pointerProperties,
2005 mLastCookedState.cookedPointerData.pointerCoords,
2006 mLastCookedState.cookedPointerData.idToIndex,
2007 dispatchedIdBits, upId, mOrientedXPrecision,
2008 mOrientedYPrecision, mDownTime,
2009 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002010 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002011 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002012 }
2013
2014 // Dispatch move events if any of the remaining pointers moved from their old locations.
2015 // Although applications receive new locations as part of individual pointer up
2016 // events, they do not generally handle them except when presented in a move event.
2017 if (moveNeeded && !moveIdBits.isEmpty()) {
2018 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002019 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2020 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2021 mCurrentCookedState.cookedPointerData.pointerProperties,
2022 mCurrentCookedState.cookedPointerData.pointerCoords,
2023 mCurrentCookedState.cookedPointerData.idToIndex,
2024 dispatchedIdBits, -1, mOrientedXPrecision,
2025 mOrientedYPrecision, mDownTime,
2026 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002027 }
2028
2029 // Dispatch pointer down events using the new pointer locations.
2030 while (!downIdBits.isEmpty()) {
2031 uint32_t downId = downIdBits.clearFirstMarkedBit();
2032 dispatchedIdBits.markBit(downId);
2033
2034 if (dispatchedIdBits.count() == 1) {
2035 // First pointer is going down. Set down time.
2036 mDownTime = when;
2037 }
2038
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002039 out.push_back(
2040 dispatchMotion(when, readTime, policyFlags, mSource,
2041 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2042 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2043 mCurrentCookedState.cookedPointerData.pointerCoords,
2044 mCurrentCookedState.cookedPointerData.idToIndex,
2045 dispatchedIdBits, downId, mOrientedXPrecision,
2046 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002047 }
2048 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002049 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002050}
2051
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002052std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2053 uint32_t policyFlags) {
2054 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002055 if (mSentHoverEnter &&
2056 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2057 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2058 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002059 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2060 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2061 mLastCookedState.buttonState, 0,
2062 mLastCookedState.cookedPointerData.pointerProperties,
2063 mLastCookedState.cookedPointerData.pointerCoords,
2064 mLastCookedState.cookedPointerData.idToIndex,
2065 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2066 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2067 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002068 mSentHoverEnter = false;
2069 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002070 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002071}
2072
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002073std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2074 uint32_t policyFlags) {
2075 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002076 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2077 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2078 int32_t metaState = getContext()->getGlobalMetaState();
2079 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002080 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2081 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2082 mCurrentRawState.buttonState, 0,
2083 mCurrentCookedState.cookedPointerData.pointerProperties,
2084 mCurrentCookedState.cookedPointerData.pointerCoords,
2085 mCurrentCookedState.cookedPointerData.idToIndex,
2086 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2087 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2088 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089 mSentHoverEnter = true;
2090 }
2091
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002092 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2093 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2094 mCurrentRawState.buttonState, 0,
2095 mCurrentCookedState.cookedPointerData.pointerProperties,
2096 mCurrentCookedState.cookedPointerData.pointerCoords,
2097 mCurrentCookedState.cookedPointerData.idToIndex,
2098 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2099 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2100 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002101 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002102 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002103}
2104
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002105std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2106 uint32_t policyFlags) {
2107 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002108 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2109 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2110 const int32_t metaState = getContext()->getGlobalMetaState();
2111 int32_t buttonState = mLastCookedState.buttonState;
2112 while (!releasedButtons.isEmpty()) {
2113 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2114 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002115 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2116 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2117 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002118 mLastCookedState.cookedPointerData.pointerProperties,
2119 mLastCookedState.cookedPointerData.pointerCoords,
2120 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002121 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2122 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002123 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002124 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002125}
2126
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002127std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2128 uint32_t policyFlags) {
2129 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002130 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2131 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2132 const int32_t metaState = getContext()->getGlobalMetaState();
2133 int32_t buttonState = mLastCookedState.buttonState;
2134 while (!pressedButtons.isEmpty()) {
2135 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2136 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002137 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2138 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2139 buttonState, 0,
2140 mCurrentCookedState.cookedPointerData.pointerProperties,
2141 mCurrentCookedState.cookedPointerData.pointerCoords,
2142 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2143 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2144 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002145 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002146 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002147}
2148
2149const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2150 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2151 return cookedPointerData.touchingIdBits;
2152 }
2153 return cookedPointerData.hoveringIdBits;
2154}
2155
2156void TouchInputMapper::cookPointerData() {
2157 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2158
2159 mCurrentCookedState.cookedPointerData.clear();
2160 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2161 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2162 mCurrentRawState.rawPointerData.hoveringIdBits;
2163 mCurrentCookedState.cookedPointerData.touchingIdBits =
2164 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002165 mCurrentCookedState.cookedPointerData.canceledIdBits =
2166 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002167
2168 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2169 mCurrentCookedState.buttonState = 0;
2170 } else {
2171 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2172 }
2173
2174 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002175 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002176 for (uint32_t i = 0; i < currentPointerCount; i++) {
2177 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2178
2179 // Size
2180 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2181 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002182 case Calibration::SizeCalibration::GEOMETRIC:
2183 case Calibration::SizeCalibration::DIAMETER:
2184 case Calibration::SizeCalibration::BOX:
2185 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002186 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2187 touchMajor = in.touchMajor;
2188 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2189 toolMajor = in.toolMajor;
2190 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2191 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2192 : in.touchMajor;
2193 } else if (mRawPointerAxes.touchMajor.valid) {
2194 toolMajor = touchMajor = in.touchMajor;
2195 toolMinor = touchMinor =
2196 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2197 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2198 : in.touchMajor;
2199 } else if (mRawPointerAxes.toolMajor.valid) {
2200 touchMajor = toolMajor = in.toolMajor;
2201 touchMinor = toolMinor =
2202 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2203 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2204 : in.toolMajor;
2205 } else {
2206 ALOG_ASSERT(false,
2207 "No touch or tool axes. "
2208 "Size calibration should have been resolved to NONE.");
2209 touchMajor = 0;
2210 touchMinor = 0;
2211 toolMajor = 0;
2212 toolMinor = 0;
2213 size = 0;
2214 }
2215
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002216 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002217 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2218 if (touchingCount > 1) {
2219 touchMajor /= touchingCount;
2220 touchMinor /= touchingCount;
2221 toolMajor /= touchingCount;
2222 toolMinor /= touchingCount;
2223 size /= touchingCount;
2224 }
2225 }
2226
Michael Wright227c5542020-07-02 18:30:52 +01002227 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002228 touchMajor *= mGeometricScale;
2229 touchMinor *= mGeometricScale;
2230 toolMajor *= mGeometricScale;
2231 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002232 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002233 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2234 touchMinor = touchMajor;
2235 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2236 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002237 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002238 touchMinor = touchMajor;
2239 toolMinor = toolMajor;
2240 }
2241
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002242 mCalibration.applySizeScaleAndBias(touchMajor);
2243 mCalibration.applySizeScaleAndBias(touchMinor);
2244 mCalibration.applySizeScaleAndBias(toolMajor);
2245 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002246 size *= mSizeScale;
2247 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002248 case Calibration::SizeCalibration::DEFAULT:
2249 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2250 break;
2251 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002252 touchMajor = 0;
2253 touchMinor = 0;
2254 toolMajor = 0;
2255 toolMinor = 0;
2256 size = 0;
2257 break;
2258 }
2259
2260 // Pressure
2261 float pressure;
2262 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002263 case Calibration::PressureCalibration::PHYSICAL:
2264 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002265 pressure = in.pressure * mPressureScale;
2266 break;
2267 default:
2268 pressure = in.isHovering ? 0 : 1;
2269 break;
2270 }
2271
2272 // Tilt and Orientation
2273 float tilt;
2274 float orientation;
2275 if (mHaveTilt) {
2276 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2277 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2278 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2279 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2280 } else {
2281 tilt = 0;
2282
2283 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002284 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002285 orientation = in.orientation * mOrientationScale;
2286 break;
Michael Wright227c5542020-07-02 18:30:52 +01002287 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002288 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2289 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2290 if (c1 != 0 || c2 != 0) {
2291 orientation = atan2f(c1, c2) * 0.5f;
2292 float confidence = hypotf(c1, c2);
2293 float scale = 1.0f + confidence / 16.0f;
2294 touchMajor *= scale;
2295 touchMinor /= scale;
2296 toolMajor *= scale;
2297 toolMinor /= scale;
2298 } else {
2299 orientation = 0;
2300 }
2301 break;
2302 }
2303 default:
2304 orientation = 0;
2305 }
2306 }
2307
2308 // Distance
2309 float distance;
2310 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002311 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002312 distance = in.distance * mDistanceScale;
2313 break;
2314 default:
2315 distance = 0;
2316 }
2317
2318 // Coverage
2319 int32_t rawLeft, rawTop, rawRight, rawBottom;
2320 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002321 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002322 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2323 rawRight = in.toolMinor & 0x0000ffff;
2324 rawBottom = in.toolMajor & 0x0000ffff;
2325 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2326 break;
2327 default:
2328 rawLeft = rawTop = rawRight = rawBottom = 0;
2329 break;
2330 }
2331
2332 // Adjust X,Y coords for device calibration
2333 // TODO: Adjust coverage coords?
2334 float xTransformed = in.x, yTransformed = in.y;
2335 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002336 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002337
Prabir Pradhan1728b212021-10-19 16:00:03 -07002338 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339 float left, top, right, bottom;
2340
Prabir Pradhan1728b212021-10-19 16:00:03 -07002341 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002342 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002343 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2344 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2345 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2346 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002348 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002350 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 }
2352 break;
2353 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2355 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002356 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2357 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002359 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002360 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002361 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 }
2363 break;
2364 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2366 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002367 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2368 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002370 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002372 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 }
2374 break;
2375 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002376 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2377 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2378 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2379 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 break;
2381 }
2382
2383 // Write output coords.
2384 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2385 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002386 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2387 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2389 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2390 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2391 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2392 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2393 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2394 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002395 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2397 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2398 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2400 } else {
2401 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2402 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2403 }
2404
Chris Ye364fdb52020-08-05 15:07:56 -07002405 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002406 uint32_t id = in.id;
2407 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2408 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2409 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2410 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2411 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2412 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2413 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2414 }
2415
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002416 // Write output properties.
2417 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 properties.clear();
2419 properties.id = id;
2420 properties.toolType = in.toolType;
2421
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002422 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002423 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002424 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 }
2426}
2427
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002428std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2429 uint32_t policyFlags,
2430 PointerUsage pointerUsage) {
2431 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002433 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 mPointerUsage = pointerUsage;
2435 }
2436
2437 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002438 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002439 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 break;
Michael Wright227c5542020-07-02 18:30:52 +01002441 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002442 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 break;
Michael Wright227c5542020-07-02 18:30:52 +01002444 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002445 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002446 break;
Michael Wright227c5542020-07-02 18:30:52 +01002447 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 break;
2449 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002450 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451}
2452
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002453std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2454 uint32_t policyFlags) {
2455 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002457 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002458 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459 break;
Michael Wright227c5542020-07-02 18:30:52 +01002460 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002461 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462 break;
Michael Wright227c5542020-07-02 18:30:52 +01002463 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002464 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 break;
Michael Wright227c5542020-07-02 18:30:52 +01002466 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 break;
2468 }
2469
Michael Wright227c5542020-07-02 18:30:52 +01002470 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002471 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472}
2473
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002474std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2475 uint32_t policyFlags,
2476 bool isTimeout) {
2477 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 // Update current gesture coordinates.
2479 bool cancelPreviousGesture, finishPreviousGesture;
2480 bool sendEvents =
2481 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2482 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002483 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002484 }
2485 if (finishPreviousGesture) {
2486 cancelPreviousGesture = false;
2487 }
2488
2489 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002490 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002491 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002492 if (finishPreviousGesture || cancelPreviousGesture) {
2493 mPointerController->clearSpots();
2494 }
2495
Michael Wright227c5542020-07-02 18:30:52 +01002496 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002497 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2498 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002499 mPointerGesture.currentGestureIdBits,
2500 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002501 }
2502 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002503 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 }
2505
2506 // Show or hide the pointer if needed.
2507 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002508 case PointerGesture::Mode::NEUTRAL:
2509 case PointerGesture::Mode::QUIET:
2510 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2511 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002513 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 }
2515 break;
Michael Wright227c5542020-07-02 18:30:52 +01002516 case PointerGesture::Mode::TAP:
2517 case PointerGesture::Mode::TAP_DRAG:
2518 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2519 case PointerGesture::Mode::HOVER:
2520 case PointerGesture::Mode::PRESS:
2521 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 // Unfade the pointer when the current gesture manipulates the
2523 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002524 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002525 break;
Michael Wright227c5542020-07-02 18:30:52 +01002526 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002527 // Fade the pointer when the current gesture manipulates a different
2528 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002529 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002530 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002531 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002532 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002533 }
2534 break;
2535 }
2536
2537 // Send events!
2538 int32_t metaState = getContext()->getGlobalMetaState();
2539 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002540 const MotionClassification classification =
2541 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2542 ? MotionClassification::TWO_FINGER_SWIPE
2543 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002545 uint32_t flags = 0;
2546
2547 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2548 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2549 }
2550
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002551 // Update last coordinates of pointers that have moved so that we observe the new
2552 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002553 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2554 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2555 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2556 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2557 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2558 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002559 bool moveNeeded = false;
2560 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2561 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2562 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2563 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2564 mPointerGesture.lastGestureIdBits.value);
2565 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2566 mPointerGesture.currentGestureCoords,
2567 mPointerGesture.currentGestureIdToIndex,
2568 mPointerGesture.lastGestureProperties,
2569 mPointerGesture.lastGestureCoords,
2570 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2571 if (buttonState != mLastCookedState.buttonState) {
2572 moveNeeded = true;
2573 }
2574 }
2575
2576 // Send motion events for all pointers that went up or were canceled.
2577 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2578 if (!dispatchedGestureIdBits.isEmpty()) {
2579 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002580 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002581 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002582 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002583 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2584 mPointerGesture.lastGestureProperties,
2585 mPointerGesture.lastGestureCoords,
2586 mPointerGesture.lastGestureIdToIndex,
2587 dispatchedGestureIdBits, -1, 0, 0,
2588 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002589
2590 dispatchedGestureIdBits.clear();
2591 } else {
2592 BitSet32 upGestureIdBits;
2593 if (finishPreviousGesture) {
2594 upGestureIdBits = dispatchedGestureIdBits;
2595 } else {
2596 upGestureIdBits.value =
2597 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2598 }
2599 while (!upGestureIdBits.isEmpty()) {
2600 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2601
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002602 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2603 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2604 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2605 mPointerGesture.lastGestureProperties,
2606 mPointerGesture.lastGestureCoords,
2607 mPointerGesture.lastGestureIdToIndex,
2608 dispatchedGestureIdBits, id, 0, 0,
2609 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002610
2611 dispatchedGestureIdBits.clearBit(id);
2612 }
2613 }
2614 }
2615
2616 // Send motion events for all pointers that moved.
2617 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002618 out.push_back(
2619 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2620 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2621 mPointerGesture.currentGestureProperties,
2622 mPointerGesture.currentGestureCoords,
2623 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2624 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002625 }
2626
2627 // Send motion events for all pointers that went down.
2628 if (down) {
2629 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2630 ~dispatchedGestureIdBits.value);
2631 while (!downGestureIdBits.isEmpty()) {
2632 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2633 dispatchedGestureIdBits.markBit(id);
2634
2635 if (dispatchedGestureIdBits.count() == 1) {
2636 mPointerGesture.downTime = when;
2637 }
2638
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002639 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2640 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2641 buttonState, 0, mPointerGesture.currentGestureProperties,
2642 mPointerGesture.currentGestureCoords,
2643 mPointerGesture.currentGestureIdToIndex,
2644 dispatchedGestureIdBits, id, 0, 0,
2645 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002646 }
2647 }
2648
2649 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002650 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002651 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2652 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2653 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2654 mPointerGesture.currentGestureProperties,
2655 mPointerGesture.currentGestureCoords,
2656 mPointerGesture.currentGestureIdToIndex,
2657 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2658 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002659 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2660 // Synthesize a hover move event after all pointers go up to indicate that
2661 // the pointer is hovering again even if the user is not currently touching
2662 // the touch pad. This ensures that a view will receive a fresh hover enter
2663 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002664 float x, y;
2665 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002666
2667 PointerProperties pointerProperties;
2668 pointerProperties.clear();
2669 pointerProperties.id = 0;
2670 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2671
2672 PointerCoords pointerCoords;
2673 pointerCoords.clear();
2674 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2675 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2676
2677 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002678 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2679 mSource, displayId, policyFlags,
2680 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2681 buttonState, MotionClassification::NONE,
2682 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2683 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2684 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002685 }
2686
2687 // Update state.
2688 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2689 if (!down) {
2690 mPointerGesture.lastGestureIdBits.clear();
2691 } else {
2692 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2693 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2694 uint32_t id = idBits.clearFirstMarkedBit();
2695 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2696 mPointerGesture.lastGestureProperties[index].copyFrom(
2697 mPointerGesture.currentGestureProperties[index]);
2698 mPointerGesture.lastGestureCoords[index].copyFrom(
2699 mPointerGesture.currentGestureCoords[index]);
2700 mPointerGesture.lastGestureIdToIndex[id] = index;
2701 }
2702 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002703 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002704}
2705
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002706std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2707 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002708 const MotionClassification classification =
2709 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2710 ? MotionClassification::TWO_FINGER_SWIPE
2711 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002712 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002713 // Cancel previously dispatches pointers.
2714 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2715 int32_t metaState = getContext()->getGlobalMetaState();
2716 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002717 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002718 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2719 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002720 mPointerGesture.lastGestureProperties,
2721 mPointerGesture.lastGestureCoords,
2722 mPointerGesture.lastGestureIdToIndex,
2723 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2724 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002725 }
2726
2727 // Reset the current pointer gesture.
2728 mPointerGesture.reset();
2729 mPointerVelocityControl.reset();
2730
2731 // Remove any current spots.
2732 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002733 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002734 mPointerController->clearSpots();
2735 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002736 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002737}
2738
2739bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2740 bool* outFinishPreviousGesture, bool isTimeout) {
2741 *outCancelPreviousGesture = false;
2742 *outFinishPreviousGesture = false;
2743
2744 // Handle TAP timeout.
2745 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002746 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002747
Michael Wright227c5542020-07-02 18:30:52 +01002748 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002749 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2750 // The tap/drag timeout has not yet expired.
2751 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2752 mConfig.pointerGestureTapDragInterval);
2753 } else {
2754 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002755 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002756 *outFinishPreviousGesture = true;
2757
2758 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002759 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002760 mPointerGesture.currentGestureIdBits.clear();
2761
2762 mPointerVelocityControl.reset();
2763 return true;
2764 }
2765 }
2766
2767 // We did not handle this timeout.
2768 return false;
2769 }
2770
2771 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2772 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2773
2774 // Update the velocity tracker.
2775 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002776 std::vector<float> positionsX;
2777 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002778 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002779 uint32_t id = idBits.clearFirstMarkedBit();
2780 const RawPointerData::Pointer& pointer =
2781 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002782 positionsX.push_back(pointer.x * mPointerXMovementScale);
2783 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002784 }
2785 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002786 {{AMOTION_EVENT_AXIS_X, positionsX},
2787 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 }
2789
2790 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2791 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002792 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2793 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2794 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 mPointerGesture.resetTap();
2796 }
2797
2798 // Pick a new active touch id if needed.
2799 // Choose an arbitrary pointer that just went down, if there is one.
2800 // Otherwise choose an arbitrary remaining pointer.
2801 // This guarantees we always have an active touch id when there is at least one pointer.
2802 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002803 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002804 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002805 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 mPointerGesture.firstTouchTime = when;
2807 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002808 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2809 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2810 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2811 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002812 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002813 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002814
2815 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002816 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002817 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002818 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2819 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2820 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002821 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822 *outFinishPreviousGesture = true;
2823 }
2824
2825 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002826 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002827 mPointerGesture.currentGestureIdBits.clear();
2828
2829 mPointerVelocityControl.reset();
2830 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2831 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2832 // The pointer follows the active touch point.
2833 // Emit DOWN, MOVE, UP events at the pointer location.
2834 //
2835 // Only the active touch matters; other fingers are ignored. This policy helps
2836 // to handle the case where the user places a second finger on the touch pad
2837 // to apply the necessary force to depress an integrated button below the surface.
2838 // We don't want the second finger to be delivered to applications.
2839 //
2840 // For this to work well, we need to make sure to track the pointer that is really
2841 // active. If the user first puts one finger down to click then adds another
2842 // finger to drag then the active pointer should switch to the finger that is
2843 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002844 ALOGD_IF(DEBUG_GESTURES,
2845 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2846 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002847 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002848 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 *outFinishPreviousGesture = true;
2850 mPointerGesture.activeGestureId = 0;
2851 }
2852
2853 // Switch pointers if needed.
2854 // Find the fastest pointer and follow it.
2855 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002856 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002858 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002859 ALOGD_IF(DEBUG_GESTURES,
2860 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2861 "bestSpeed=%0.3f",
2862 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002863 }
2864 }
2865
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002866 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 // When using spots, the click will occur at the position of the anchor
2868 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002869 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002870 } else {
2871 mPointerVelocityControl.reset();
2872 }
2873
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002874 float x, y;
2875 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002876
Michael Wright227c5542020-07-02 18:30:52 +01002877 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878 mPointerGesture.currentGestureIdBits.clear();
2879 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2880 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2881 mPointerGesture.currentGestureProperties[0].clear();
2882 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2883 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2884 mPointerGesture.currentGestureCoords[0].clear();
2885 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2886 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2887 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2888 } else if (currentFingerCount == 0) {
2889 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002890 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 *outFinishPreviousGesture = true;
2892 }
2893
2894 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2895 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2896 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002897 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2898 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002899 lastFingerCount == 1) {
2900 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002901 float x, y;
2902 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2904 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002905 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906
2907 mPointerGesture.tapUpTime = when;
2908 getContext()->requestTimeoutAtTime(when +
2909 mConfig.pointerGestureTapDragInterval);
2910
2911 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002912 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913 mPointerGesture.currentGestureIdBits.clear();
2914 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2915 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2916 mPointerGesture.currentGestureProperties[0].clear();
2917 mPointerGesture.currentGestureProperties[0].id =
2918 mPointerGesture.activeGestureId;
2919 mPointerGesture.currentGestureProperties[0].toolType =
2920 AMOTION_EVENT_TOOL_TYPE_FINGER;
2921 mPointerGesture.currentGestureCoords[0].clear();
2922 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2923 mPointerGesture.tapX);
2924 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2925 mPointerGesture.tapY);
2926 mPointerGesture.currentGestureCoords[0]
2927 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2928
2929 tapped = true;
2930 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002931 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2932 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002933 }
2934 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002935 if (DEBUG_GESTURES) {
2936 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2937 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2938 (when - mPointerGesture.tapDownTime) * 0.000001f);
2939 } else {
2940 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2941 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002942 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943 }
2944 }
2945
2946 mPointerVelocityControl.reset();
2947
2948 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002949 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002951 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 mPointerGesture.currentGestureIdBits.clear();
2953 }
2954 } else if (currentFingerCount == 1) {
2955 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2956 // The pointer follows the active touch point.
2957 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2958 // When in TAP_DRAG, emit MOVE events at the pointer location.
2959 ALOG_ASSERT(activeTouchId >= 0);
2960
Michael Wright227c5542020-07-02 18:30:52 +01002961 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2962 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002963 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002964 float x, y;
2965 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002966 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2967 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002968 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002969 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002970 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2971 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002972 }
2973 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002974 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2975 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002976 }
Michael Wright227c5542020-07-02 18:30:52 +01002977 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2978 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979 }
2980
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002982 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002983 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984 } else {
2985 mPointerVelocityControl.reset();
2986 }
2987
2988 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002989 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002990 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 down = true;
2992 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002993 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002994 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002995 *outFinishPreviousGesture = true;
2996 }
2997 mPointerGesture.activeGestureId = 0;
2998 down = false;
2999 }
3000
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003001 float x, y;
3002 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003
3004 mPointerGesture.currentGestureIdBits.clear();
3005 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3006 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3007 mPointerGesture.currentGestureProperties[0].clear();
3008 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3009 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3010 mPointerGesture.currentGestureCoords[0].clear();
3011 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3012 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3013 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3014 down ? 1.0f : 0.0f);
3015
3016 if (lastFingerCount == 0 && currentFingerCount != 0) {
3017 mPointerGesture.resetTap();
3018 mPointerGesture.tapDownTime = when;
3019 mPointerGesture.tapX = x;
3020 mPointerGesture.tapY = y;
3021 }
3022 } else {
3023 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003024 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003025 }
3026
3027 mPointerController->setButtonState(mCurrentRawState.buttonState);
3028
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003029 if (DEBUG_GESTURES) {
3030 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3031 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3032 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3033 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3034 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3035 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3036 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3037 uint32_t id = idBits.clearFirstMarkedBit();
3038 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3039 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3040 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3041 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3042 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3043 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3044 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3045 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3046 }
3047 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3048 uint32_t id = idBits.clearFirstMarkedBit();
3049 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3050 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3051 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3052 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3053 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3054 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3055 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3056 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3057 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003058 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003059 return true;
3060}
3061
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003062bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3063 if (mPointerGesture.activeTouchId < 0) {
3064 mPointerGesture.resetQuietTime();
3065 return false;
3066 }
3067
3068 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3069 return true;
3070 }
3071
3072 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3073 bool isQuietTime = false;
3074 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3075 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3076 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3077 currentFingerCount < 2) {
3078 // Enter quiet time when exiting swipe or freeform state.
3079 // This is to prevent accidentally entering the hover state and flinging the
3080 // pointer when finishing a swipe and there is still one pointer left onscreen.
3081 isQuietTime = true;
3082 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3083 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3084 // Enter quiet time when releasing the button and there are still two or more
3085 // fingers down. This may indicate that one finger was used to press the button
3086 // but it has not gone up yet.
3087 isQuietTime = true;
3088 }
3089 if (isQuietTime) {
3090 mPointerGesture.quietTime = when;
3091 }
3092 return isQuietTime;
3093}
3094
3095std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3096 int32_t bestId = -1;
3097 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3098 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3099 uint32_t id = idBits.clearFirstMarkedBit();
3100 std::optional<float> vx =
3101 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3102 std::optional<float> vy =
3103 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3104 if (vx && vy) {
3105 float speed = hypotf(*vx, *vy);
3106 if (speed > bestSpeed) {
3107 bestId = id;
3108 bestSpeed = speed;
3109 }
3110 }
3111 }
3112 return std::make_pair(bestId, bestSpeed);
3113}
3114
3115void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3116 bool* finishPreviousGesture) {
3117 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3118 // to move before deciding what to do.
3119 //
3120 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3121 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3122 // just a press or long-press at the pointer location.
3123 //
3124 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3125 // pointer location.
3126 //
3127 // When the two fingers move enough or when additional fingers are added, we make a decision to
3128 // transition into SWIPE or FREEFORM mode accordingly.
3129 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3130 ALOG_ASSERT(activeTouchId >= 0);
3131
3132 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3133 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3134 bool settled =
3135 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3136 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3137 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3138 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3139 *finishPreviousGesture = true;
3140 } else if (!settled && currentFingerCount > lastFingerCount) {
3141 // Additional pointers have gone down but not yet settled.
3142 // Reset the gesture.
3143 ALOGD_IF(DEBUG_GESTURES,
3144 "Gestures: Resetting gesture since additional pointers went down for "
3145 "MULTITOUCH, settle time remaining %0.3fms",
3146 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3147 when) * 0.000001f);
3148 *cancelPreviousGesture = true;
3149 } else {
3150 // Continue previous gesture.
3151 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3152 }
3153
3154 if (*finishPreviousGesture || *cancelPreviousGesture) {
3155 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3156 mPointerGesture.activeGestureId = 0;
3157 mPointerGesture.referenceIdBits.clear();
3158 mPointerVelocityControl.reset();
3159
3160 // Use the centroid and pointer location as the reference points for the gesture.
3161 ALOGD_IF(DEBUG_GESTURES,
3162 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3163 "%0.3fms",
3164 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3165 when) * 0.000001f);
3166 mCurrentRawState.rawPointerData
3167 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3168 &mPointerGesture.referenceTouchY);
3169 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3170 &mPointerGesture.referenceGestureY);
3171 }
3172
3173 // Clear the reference deltas for fingers not yet included in the reference calculation.
3174 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3175 ~mPointerGesture.referenceIdBits.value);
3176 !idBits.isEmpty();) {
3177 uint32_t id = idBits.clearFirstMarkedBit();
3178 mPointerGesture.referenceDeltas[id].dx = 0;
3179 mPointerGesture.referenceDeltas[id].dy = 0;
3180 }
3181 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3182
3183 // Add delta for all fingers and calculate a common movement delta.
3184 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3185 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3186 mCurrentCookedState.fingerIdBits.value);
3187 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3188 bool first = (idBits == commonIdBits);
3189 uint32_t id = idBits.clearFirstMarkedBit();
3190 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3191 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3192 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3193 delta.dx += cpd.x - lpd.x;
3194 delta.dy += cpd.y - lpd.y;
3195
3196 if (first) {
3197 commonDeltaRawX = delta.dx;
3198 commonDeltaRawY = delta.dy;
3199 } else {
3200 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3201 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3202 }
3203 }
3204
3205 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3206 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3207 float dist[MAX_POINTER_ID + 1];
3208 int32_t distOverThreshold = 0;
3209 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3210 uint32_t id = idBits.clearFirstMarkedBit();
3211 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3212 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3213 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3214 distOverThreshold += 1;
3215 }
3216 }
3217
3218 // Only transition when at least two pointers have moved further than
3219 // the minimum distance threshold.
3220 if (distOverThreshold >= 2) {
3221 if (currentFingerCount > 2) {
3222 // There are more than two pointers, switch to FREEFORM.
3223 ALOGD_IF(DEBUG_GESTURES,
3224 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3225 currentFingerCount);
3226 *cancelPreviousGesture = true;
3227 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3228 } else {
3229 // There are exactly two pointers.
3230 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3231 uint32_t id1 = idBits.clearFirstMarkedBit();
3232 uint32_t id2 = idBits.firstMarkedBit();
3233 const RawPointerData::Pointer& p1 =
3234 mCurrentRawState.rawPointerData.pointerForId(id1);
3235 const RawPointerData::Pointer& p2 =
3236 mCurrentRawState.rawPointerData.pointerForId(id2);
3237 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3238 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3239 // There are two pointers but they are too far apart for a SWIPE,
3240 // switch to FREEFORM.
3241 ALOGD_IF(DEBUG_GESTURES,
3242 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3243 mutualDistance, mPointerGestureMaxSwipeWidth);
3244 *cancelPreviousGesture = true;
3245 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3246 } else {
3247 // There are two pointers. Wait for both pointers to start moving
3248 // before deciding whether this is a SWIPE or FREEFORM gesture.
3249 float dist1 = dist[id1];
3250 float dist2 = dist[id2];
3251 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3252 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3253 // Calculate the dot product of the displacement vectors.
3254 // When the vectors are oriented in approximately the same direction,
3255 // the angle betweeen them is near zero and the cosine of the angle
3256 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3257 // mag(v2).
3258 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3259 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3260 float dx1 = delta1.dx * mPointerXZoomScale;
3261 float dy1 = delta1.dy * mPointerYZoomScale;
3262 float dx2 = delta2.dx * mPointerXZoomScale;
3263 float dy2 = delta2.dy * mPointerYZoomScale;
3264 float dot = dx1 * dx2 + dy1 * dy2;
3265 float cosine = dot / (dist1 * dist2); // denominator always > 0
3266 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3267 // Pointers are moving in the same direction. Switch to SWIPE.
3268 ALOGD_IF(DEBUG_GESTURES,
3269 "Gestures: PRESS transitioned to SWIPE, "
3270 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3271 "cosine %0.3f >= %0.3f",
3272 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3273 mConfig.pointerGestureMultitouchMinDistance, cosine,
3274 mConfig.pointerGestureSwipeTransitionAngleCosine);
3275 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3276 } else {
3277 // Pointers are moving in different directions. Switch to FREEFORM.
3278 ALOGD_IF(DEBUG_GESTURES,
3279 "Gestures: PRESS transitioned to FREEFORM, "
3280 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3281 "cosine %0.3f < %0.3f",
3282 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3283 mConfig.pointerGestureMultitouchMinDistance, cosine,
3284 mConfig.pointerGestureSwipeTransitionAngleCosine);
3285 *cancelPreviousGesture = true;
3286 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3287 }
3288 }
3289 }
3290 }
3291 }
3292 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3293 // Switch from SWIPE to FREEFORM if additional pointers go down.
3294 // Cancel previous gesture.
3295 if (currentFingerCount > 2) {
3296 ALOGD_IF(DEBUG_GESTURES,
3297 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3298 currentFingerCount);
3299 *cancelPreviousGesture = true;
3300 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3301 }
3302 }
3303
3304 // Move the reference points based on the overall group motion of the fingers
3305 // except in PRESS mode while waiting for a transition to occur.
3306 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3307 (commonDeltaRawX || commonDeltaRawY)) {
3308 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3309 uint32_t id = idBits.clearFirstMarkedBit();
3310 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3311 delta.dx = 0;
3312 delta.dy = 0;
3313 }
3314
3315 mPointerGesture.referenceTouchX += commonDeltaRawX;
3316 mPointerGesture.referenceTouchY += commonDeltaRawY;
3317
3318 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3319 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3320
3321 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3322 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3323
3324 mPointerGesture.referenceGestureX += commonDeltaX;
3325 mPointerGesture.referenceGestureY += commonDeltaY;
3326 }
3327
3328 // Report gestures.
3329 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3330 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3331 // PRESS or SWIPE mode.
3332 ALOGD_IF(DEBUG_GESTURES,
3333 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3334 "currentTouchPointerCount=%d",
3335 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3336 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3337
3338 mPointerGesture.currentGestureIdBits.clear();
3339 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3340 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3341 mPointerGesture.currentGestureProperties[0].clear();
3342 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3343 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3344 mPointerGesture.currentGestureCoords[0].clear();
3345 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3346 mPointerGesture.referenceGestureX);
3347 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3348 mPointerGesture.referenceGestureY);
3349 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3350 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3351 float xOffset = static_cast<float>(commonDeltaRawX) /
3352 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3353 float yOffset = static_cast<float>(commonDeltaRawY) /
3354 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3355 mPointerGesture.currentGestureCoords[0]
3356 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3357 mPointerGesture.currentGestureCoords[0]
3358 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3359 }
3360 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3361 // FREEFORM mode.
3362 ALOGD_IF(DEBUG_GESTURES,
3363 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3364 "currentTouchPointerCount=%d",
3365 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3366 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3367
3368 mPointerGesture.currentGestureIdBits.clear();
3369
3370 BitSet32 mappedTouchIdBits;
3371 BitSet32 usedGestureIdBits;
3372 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3373 // Initially, assign the active gesture id to the active touch point
3374 // if there is one. No other touch id bits are mapped yet.
3375 if (!*cancelPreviousGesture) {
3376 mappedTouchIdBits.markBit(activeTouchId);
3377 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3378 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3379 mPointerGesture.activeGestureId;
3380 } else {
3381 mPointerGesture.activeGestureId = -1;
3382 }
3383 } else {
3384 // Otherwise, assume we mapped all touches from the previous frame.
3385 // Reuse all mappings that are still applicable.
3386 mappedTouchIdBits.value =
3387 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3388 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3389
3390 // Check whether we need to choose a new active gesture id because the
3391 // current went went up.
3392 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3393 ~mCurrentCookedState.fingerIdBits.value);
3394 !upTouchIdBits.isEmpty();) {
3395 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3396 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3397 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3398 mPointerGesture.activeGestureId = -1;
3399 break;
3400 }
3401 }
3402 }
3403
3404 ALOGD_IF(DEBUG_GESTURES,
3405 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3406 "activeGestureId=%d",
3407 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3408
3409 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3410 for (uint32_t i = 0; i < currentFingerCount; i++) {
3411 uint32_t touchId = idBits.clearFirstMarkedBit();
3412 uint32_t gestureId;
3413 if (!mappedTouchIdBits.hasBit(touchId)) {
3414 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3415 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3416 ALOGD_IF(DEBUG_GESTURES,
3417 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3418 gestureId);
3419 } else {
3420 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3421 ALOGD_IF(DEBUG_GESTURES,
3422 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3423 touchId, gestureId);
3424 }
3425 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3426 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3427
3428 const RawPointerData::Pointer& pointer =
3429 mCurrentRawState.rawPointerData.pointerForId(touchId);
3430 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3431 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3432 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3433
3434 mPointerGesture.currentGestureProperties[i].clear();
3435 mPointerGesture.currentGestureProperties[i].id = gestureId;
3436 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3437 mPointerGesture.currentGestureCoords[i].clear();
3438 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3439 mPointerGesture.referenceGestureX +
3440 deltaX);
3441 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3442 mPointerGesture.referenceGestureY +
3443 deltaY);
3444 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3445 }
3446
3447 if (mPointerGesture.activeGestureId < 0) {
3448 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3449 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3450 mPointerGesture.activeGestureId);
3451 }
3452 }
3453}
3454
Harry Cutts714d1ad2022-08-24 16:36:43 +00003455void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3456 const RawPointerData::Pointer& currentPointer =
3457 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3458 const RawPointerData::Pointer& lastPointer =
3459 mLastRawState.rawPointerData.pointerForId(pointerId);
3460 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3461 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3462
3463 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3464 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3465
3466 mPointerController->move(deltaX, deltaY);
3467}
3468
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003469std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3470 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003471 mPointerSimple.currentCoords.clear();
3472 mPointerSimple.currentProperties.clear();
3473
3474 bool down, hovering;
3475 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3476 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3477 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003478 mPointerController
3479 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3480 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003481
3482 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3483 down = !hovering;
3484
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003485 float x, y;
3486 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003487 mPointerSimple.currentCoords.copyFrom(
3488 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3489 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3490 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3491 mPointerSimple.currentProperties.id = 0;
3492 mPointerSimple.currentProperties.toolType =
3493 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3494 } else {
3495 down = false;
3496 hovering = false;
3497 }
3498
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003499 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003500}
3501
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003502std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3503 uint32_t policyFlags) {
3504 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003505}
3506
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003507std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3508 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509 mPointerSimple.currentCoords.clear();
3510 mPointerSimple.currentProperties.clear();
3511
3512 bool down, hovering;
3513 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3514 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003516 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517 } else {
3518 mPointerVelocityControl.reset();
3519 }
3520
3521 down = isPointerDown(mCurrentRawState.buttonState);
3522 hovering = !down;
3523
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003524 float x, y;
3525 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003526 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527 mPointerSimple.currentCoords.copyFrom(
3528 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3529 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3530 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3531 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3532 hovering ? 0.0f : 1.0f);
3533 mPointerSimple.currentProperties.id = 0;
3534 mPointerSimple.currentProperties.toolType =
3535 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3536 } else {
3537 mPointerVelocityControl.reset();
3538
3539 down = false;
3540 hovering = false;
3541 }
3542
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003543 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003544}
3545
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003546std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3547 uint32_t policyFlags) {
3548 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003549
3550 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003551
3552 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003553}
3554
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003555std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3556 uint32_t policyFlags, bool down,
3557 bool hovering) {
3558 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003559 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003560
3561 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003562 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 mPointerController->clearSpots();
3564 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003565 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003566 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003567 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003568 }
Garfield Tan9514d782020-11-10 16:37:23 -08003569 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003571 float xCursorPosition, yCursorPosition;
3572 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573
3574 if (mPointerSimple.down && !down) {
3575 mPointerSimple.down = false;
3576
3577 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003578 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3579 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3580 0, metaState, mLastRawState.buttonState,
3581 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3582 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3583 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3584 yCursorPosition, mPointerSimple.downTime,
3585 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003586 }
3587
3588 if (mPointerSimple.hovering && !hovering) {
3589 mPointerSimple.hovering = false;
3590
3591 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003592 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3593 mSource, displayId, policyFlags,
3594 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3595 mLastRawState.buttonState, MotionClassification::NONE,
3596 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3597 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3598 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3599 yCursorPosition, mPointerSimple.downTime,
3600 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003601 }
3602
3603 if (down) {
3604 if (!mPointerSimple.down) {
3605 mPointerSimple.down = true;
3606 mPointerSimple.downTime = when;
3607
3608 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003609 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3610 mSource, displayId, policyFlags,
3611 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3612 mCurrentRawState.buttonState, MotionClassification::NONE,
3613 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3614 &mPointerSimple.currentProperties,
3615 &mPointerSimple.currentCoords, mOrientedXPrecision,
3616 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3617 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003618 }
3619
3620 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003621 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3622 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3623 0, 0, metaState, mCurrentRawState.buttonState,
3624 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3625 &mPointerSimple.currentProperties,
3626 &mPointerSimple.currentCoords, mOrientedXPrecision,
3627 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3628 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629 }
3630
3631 if (hovering) {
3632 if (!mPointerSimple.hovering) {
3633 mPointerSimple.hovering = true;
3634
3635 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003636 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3637 mSource, displayId, policyFlags,
3638 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3639 mCurrentRawState.buttonState, MotionClassification::NONE,
3640 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3641 &mPointerSimple.currentProperties,
3642 &mPointerSimple.currentCoords, mOrientedXPrecision,
3643 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3644 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003645 }
3646
3647 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003648 out.push_back(
3649 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3650 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3651 metaState, mCurrentRawState.buttonState,
3652 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3653 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3654 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3655 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003656 }
3657
3658 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3659 float vscroll = mCurrentRawState.rawVScroll;
3660 float hscroll = mCurrentRawState.rawHScroll;
3661 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3662 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3663
3664 // Send scroll.
3665 PointerCoords pointerCoords;
3666 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3667 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3668 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3669
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003670 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3671 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3672 0, 0, metaState, mCurrentRawState.buttonState,
3673 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3674 &mPointerSimple.currentProperties, &pointerCoords,
3675 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3676 yCursorPosition, mPointerSimple.downTime,
3677 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003678 }
3679
3680 // Save state.
3681 if (down || hovering) {
3682 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3683 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3684 } else {
3685 mPointerSimple.reset();
3686 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003687 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003688}
3689
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003690std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3691 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003692 mPointerSimple.currentCoords.clear();
3693 mPointerSimple.currentProperties.clear();
3694
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003695 return dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696}
3697
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003698NotifyMotionArgs TouchInputMapper::dispatchMotion(
3699 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3700 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003701 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3702 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003703 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003704 PointerCoords pointerCoords[MAX_POINTERS];
3705 PointerProperties pointerProperties[MAX_POINTERS];
3706 uint32_t pointerCount = 0;
3707 while (!idBits.isEmpty()) {
3708 uint32_t id = idBits.clearFirstMarkedBit();
3709 uint32_t index = idToIndex[id];
3710 pointerProperties[pointerCount].copyFrom(properties[index]);
3711 pointerCoords[pointerCount].copyFrom(coords[index]);
3712
3713 if (changedId >= 0 && id == uint32_t(changedId)) {
3714 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3715 }
3716
3717 pointerCount += 1;
3718 }
3719
3720 ALOG_ASSERT(pointerCount != 0);
3721
3722 if (changedId >= 0 && pointerCount == 1) {
3723 // Replace initial down and final up action.
3724 // We can compare the action without masking off the changed pointer index
3725 // because we know the index is 0.
3726 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3727 action = AMOTION_EVENT_ACTION_DOWN;
3728 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003729 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3730 action = AMOTION_EVENT_ACTION_CANCEL;
3731 } else {
3732 action = AMOTION_EVENT_ACTION_UP;
3733 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003734 } else {
3735 // Can't happen.
3736 ALOG_ASSERT(false);
3737 }
3738 }
3739 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3740 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003741 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003742 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003743 }
3744 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3745 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003746 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003747 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003748 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003749 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3750 policyFlags, action, actionButton, flags, metaState, buttonState,
3751 classification, edgeFlags, pointerCount, pointerProperties,
3752 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3753 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003754}
3755
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003756std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3757 std::list<NotifyArgs> out;
3758 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3759 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3760 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003761}
3762
Prabir Pradhan1728b212021-10-19 16:00:03 -07003763// Transform input device coordinates to display panel coordinates.
3764void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003765 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3766 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3767
arthurhunga36b28e2020-12-29 20:28:15 +08003768 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3769 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3770
Prabir Pradhan1728b212021-10-19 16:00:03 -07003771 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003772 // 0 - no swap and reverse.
3773 // 90 - swap x/y and reverse y.
3774 // 180 - reverse x, y.
3775 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003776 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003777 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003778 x = xScaled;
3779 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003780 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003781 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003782 y = xScaledMax;
3783 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003784 break;
3785 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003786 x = xScaledMax;
3787 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003788 break;
3789 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003790 y = xScaled;
3791 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003792 break;
3793 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003794 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003795 }
3796}
3797
Prabir Pradhan1728b212021-10-19 16:00:03 -07003798bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003799 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3800 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3801
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003802 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003803 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003804 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003805 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003806}
3807
3808const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3809 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003810 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3811 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3812 "left=%d, top=%d, right=%d, bottom=%d",
3813 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3814 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003815
3816 if (virtualKey.isHit(x, y)) {
3817 return &virtualKey;
3818 }
3819 }
3820
3821 return nullptr;
3822}
3823
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003824void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3825 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3826 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003827
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003828 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003829
3830 if (currentPointerCount == 0) {
3831 // No pointers to assign.
3832 return;
3833 }
3834
3835 if (lastPointerCount == 0) {
3836 // All pointers are new.
3837 for (uint32_t i = 0; i < currentPointerCount; i++) {
3838 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003839 current.rawPointerData.pointers[i].id = id;
3840 current.rawPointerData.idToIndex[id] = i;
3841 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003842 }
3843 return;
3844 }
3845
3846 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003847 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003848 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003849 uint32_t id = last.rawPointerData.pointers[0].id;
3850 current.rawPointerData.pointers[0].id = id;
3851 current.rawPointerData.idToIndex[id] = 0;
3852 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003853 return;
3854 }
3855
3856 // General case.
3857 // We build a heap of squared euclidean distances between current and last pointers
3858 // associated with the current and last pointer indices. Then, we find the best
3859 // match (by distance) for each current pointer.
3860 // The pointers must have the same tool type but it is possible for them to
3861 // transition from hovering to touching or vice-versa while retaining the same id.
3862 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3863
3864 uint32_t heapSize = 0;
3865 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3866 currentPointerIndex++) {
3867 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3868 lastPointerIndex++) {
3869 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003870 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003871 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003872 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003873 if (currentPointer.toolType == lastPointer.toolType) {
3874 int64_t deltaX = currentPointer.x - lastPointer.x;
3875 int64_t deltaY = currentPointer.y - lastPointer.y;
3876
3877 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3878
3879 // Insert new element into the heap (sift up).
3880 heap[heapSize].currentPointerIndex = currentPointerIndex;
3881 heap[heapSize].lastPointerIndex = lastPointerIndex;
3882 heap[heapSize].distance = distance;
3883 heapSize += 1;
3884 }
3885 }
3886 }
3887
3888 // Heapify
3889 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3890 startIndex -= 1;
3891 for (uint32_t parentIndex = startIndex;;) {
3892 uint32_t childIndex = parentIndex * 2 + 1;
3893 if (childIndex >= heapSize) {
3894 break;
3895 }
3896
3897 if (childIndex + 1 < heapSize &&
3898 heap[childIndex + 1].distance < heap[childIndex].distance) {
3899 childIndex += 1;
3900 }
3901
3902 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3903 break;
3904 }
3905
3906 swap(heap[parentIndex], heap[childIndex]);
3907 parentIndex = childIndex;
3908 }
3909 }
3910
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003911 if (DEBUG_POINTER_ASSIGNMENT) {
3912 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3913 for (size_t i = 0; i < heapSize; i++) {
3914 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3915 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3916 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003917 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003918
3919 // Pull matches out by increasing order of distance.
3920 // To avoid reassigning pointers that have already been matched, the loop keeps track
3921 // of which last and current pointers have been matched using the matchedXXXBits variables.
3922 // It also tracks the used pointer id bits.
3923 BitSet32 matchedLastBits(0);
3924 BitSet32 matchedCurrentBits(0);
3925 BitSet32 usedIdBits(0);
3926 bool first = true;
3927 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3928 while (heapSize > 0) {
3929 if (first) {
3930 // The first time through the loop, we just consume the root element of
3931 // the heap (the one with smallest distance).
3932 first = false;
3933 } else {
3934 // Previous iterations consumed the root element of the heap.
3935 // Pop root element off of the heap (sift down).
3936 heap[0] = heap[heapSize];
3937 for (uint32_t parentIndex = 0;;) {
3938 uint32_t childIndex = parentIndex * 2 + 1;
3939 if (childIndex >= heapSize) {
3940 break;
3941 }
3942
3943 if (childIndex + 1 < heapSize &&
3944 heap[childIndex + 1].distance < heap[childIndex].distance) {
3945 childIndex += 1;
3946 }
3947
3948 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3949 break;
3950 }
3951
3952 swap(heap[parentIndex], heap[childIndex]);
3953 parentIndex = childIndex;
3954 }
3955
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003956 if (DEBUG_POINTER_ASSIGNMENT) {
3957 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3958 for (size_t j = 0; j < heapSize; j++) {
3959 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3960 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3961 heap[j].distance);
3962 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003963 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003964 }
3965
3966 heapSize -= 1;
3967
3968 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3969 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3970
3971 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3972 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3973
3974 matchedCurrentBits.markBit(currentPointerIndex);
3975 matchedLastBits.markBit(lastPointerIndex);
3976
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003977 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3978 current.rawPointerData.pointers[currentPointerIndex].id = id;
3979 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3980 current.rawPointerData.markIdBit(id,
3981 current.rawPointerData.isHovering(
3982 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003983 usedIdBits.markBit(id);
3984
Harry Cutts45483602022-08-24 14:36:48 +00003985 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3986 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3987 ", distance=%" PRIu64,
3988 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003989 break;
3990 }
3991 }
3992
3993 // Assign fresh ids to pointers that were not matched in the process.
3994 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3995 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3996 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3997
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003998 current.rawPointerData.pointers[currentPointerIndex].id = id;
3999 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4000 current.rawPointerData.markIdBit(id,
4001 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004002
Harry Cutts45483602022-08-24 14:36:48 +00004003 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4004 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4005 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004006 }
4007}
4008
4009int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4010 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4011 return AKEY_STATE_VIRTUAL;
4012 }
4013
4014 for (const VirtualKey& virtualKey : mVirtualKeys) {
4015 if (virtualKey.keyCode == keyCode) {
4016 return AKEY_STATE_UP;
4017 }
4018 }
4019
4020 return AKEY_STATE_UNKNOWN;
4021}
4022
4023int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4024 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4025 return AKEY_STATE_VIRTUAL;
4026 }
4027
4028 for (const VirtualKey& virtualKey : mVirtualKeys) {
4029 if (virtualKey.scanCode == scanCode) {
4030 return AKEY_STATE_UP;
4031 }
4032 }
4033
4034 return AKEY_STATE_UNKNOWN;
4035}
4036
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004037bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4038 const std::vector<int32_t>& keyCodes,
4039 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004040 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004041 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004042 if (virtualKey.keyCode == keyCodes[i]) {
4043 outFlags[i] = 1;
4044 }
4045 }
4046 }
4047
4048 return true;
4049}
4050
4051std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4052 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004053 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004054 return std::make_optional(mPointerController->getDisplayId());
4055 } else {
4056 return std::make_optional(mViewport.displayId);
4057 }
4058 }
4059 return std::nullopt;
4060}
4061
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004062} // namespace android