blob: 3947cf7b9f6746c82f11bf71a0846bbdb150af40 [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 Pradhan4f05b5f2022-10-11 21:24:07 +000099 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700100 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100101 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700102 mDisplayWidth(-1),
103 mDisplayHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700104 mPhysicalWidth(-1),
105 mPhysicalHeight(-1),
106 mPhysicalLeft(0),
107 mPhysicalTop(0),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700108 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109
110TouchInputMapper::~TouchInputMapper() {}
111
Philip Junker4af3b3d2021-12-14 10:36:55 +0100112uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700113 return mSource;
114}
115
116void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
117 InputMapper::populateDeviceInfo(info);
118
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000119 if (mDeviceMode == DeviceMode::DISABLED) {
120 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700121 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000122
123 info->addMotionRange(mOrientedRanges.x);
124 info->addMotionRange(mOrientedRanges.y);
125 info->addMotionRange(mOrientedRanges.pressure);
126
127 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
128 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
129 //
130 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
131 // motion, i.e. the hardware dimensions, as the finger could move completely across the
132 // touchpad in one sample cycle.
133 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
134 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
135 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
136 x.resolution);
137 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
138 y.resolution);
139 }
140
141 if (mOrientedRanges.size) {
142 info->addMotionRange(*mOrientedRanges.size);
143 }
144
145 if (mOrientedRanges.touchMajor) {
146 info->addMotionRange(*mOrientedRanges.touchMajor);
147 info->addMotionRange(*mOrientedRanges.touchMinor);
148 }
149
150 if (mOrientedRanges.toolMajor) {
151 info->addMotionRange(*mOrientedRanges.toolMajor);
152 info->addMotionRange(*mOrientedRanges.toolMinor);
153 }
154
155 if (mOrientedRanges.orientation) {
156 info->addMotionRange(*mOrientedRanges.orientation);
157 }
158
159 if (mOrientedRanges.distance) {
160 info->addMotionRange(*mOrientedRanges.distance);
161 }
162
163 if (mOrientedRanges.tilt) {
164 info->addMotionRange(*mOrientedRanges.tilt);
165 }
166
167 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
168 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
169 }
170 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
171 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
172 }
173 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
174 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
175 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
176 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
177 x.resolution);
178 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
179 y.resolution);
180 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
181 x.resolution);
182 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
183 y.resolution);
184 }
185 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000186 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700187}
188
189void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700190 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800191 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 dumpParameters(dump);
193 dumpVirtualKeys(dump);
194 dumpRawPointerAxes(dump);
195 dumpCalibration(dump);
196 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700197 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700198
199 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700200 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
201 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
202 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
203 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
204 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
205 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
206 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
207 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
208 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
209 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
210 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
211 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
212 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
213 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
214
215 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
216 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
217 mLastRawState.rawPointerData.pointerCount);
218 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
219 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
220 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
221 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
222 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
223 "toolType=%d, isHovering=%s\n",
224 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
225 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
226 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
227 pointer.distance, pointer.toolType, toString(pointer.isHovering));
228 }
229
230 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
231 mLastCookedState.buttonState);
232 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
233 mLastCookedState.cookedPointerData.pointerCount);
234 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
235 const PointerProperties& pointerProperties =
236 mLastCookedState.cookedPointerData.pointerProperties[i];
237 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000238 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
239 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
240 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700241 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
242 "toolType=%d, isHovering=%s\n",
243 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000244 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
245 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700246 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
247 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
248 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
249 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
250 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
251 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
252 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
253 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
254 pointerProperties.toolType,
255 toString(mLastCookedState.cookedPointerData.isHovering(i)));
256 }
257
258 dump += INDENT3 "Stylus Fusion:\n";
259 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
260 toString(mExternalStylusConnected));
261 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
262 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
263 mExternalStylusFusionTimeout);
264 dump += INDENT3 "External Stylus State:\n";
265 dumpStylusState(dump, mExternalStylusState);
266
Michael Wright227c5542020-07-02 18:30:52 +0100267 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700268 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
269 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
270 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
271 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
272 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
273 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
274 }
275}
276
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700277std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
278 const InputReaderConfiguration* config,
279 uint32_t changes) {
280 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700281
282 mConfig = *config;
283
284 if (!changes) { // first time only
285 // Configure basic parameters.
286 configureParameters();
287
288 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800289 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000290 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700291
292 // Configure absolute axis information.
293 configureRawPointerAxes();
294
295 // Prepare input device calibration.
296 parseCalibration();
297 resolveCalibration();
298 }
299
300 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
301 // Update location calibration to reflect current settings
302 updateAffineTransformation();
303 }
304
305 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
306 // Update pointer speed.
307 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
308 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
309 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
310 }
311
312 bool resetNeeded = false;
313 if (!changes ||
314 (changes &
315 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800316 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700317 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
318 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
319 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700320 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700321 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700322 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700323 }
324
325 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700326 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000327
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700328 // Send reset, unless this is the first time the device has been configured,
329 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000330 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700331 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700332 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333}
334
335void TouchInputMapper::resolveExternalStylusPresence() {
336 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800337 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700338 mExternalStylusConnected = !devices.empty();
339
340 if (!mExternalStylusConnected) {
341 resetExternalStylus();
342 }
343}
344
345void TouchInputMapper::configureParameters() {
346 // Use the pointer presentation mode for devices that do not support distinct
347 // multitouch. The spot-based presentation relies on being able to accurately
348 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800349 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100350 ? Parameters::GestureMode::SINGLE_TOUCH
351 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700352
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700353 std::string gestureModeString;
354 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800355 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700356 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100357 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700358 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100359 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700360 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700361 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700362 }
363 }
364
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800365 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700366 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100367 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800368 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700369 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100370 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700371 } else {
372 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100373 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374 }
375
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800376 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700377
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700378 std::string deviceTypeString;
379 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800380 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700381 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100382 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700383 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100384 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700385 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100386 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700387 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700388 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 }
390 }
391
Michael Wright227c5542020-07-02 18:30:52 +0100392 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700393 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800394 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700395
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700396 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700397 std::string orientationString;
398 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700399 orientationString)) {
400 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
401 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
402 } else if (orientationString == "ORIENTATION_90") {
403 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
404 } else if (orientationString == "ORIENTATION_180") {
405 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
406 } else if (orientationString == "ORIENTATION_270") {
407 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
408 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700409 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700410 }
411 }
412
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700413 mParameters.hasAssociatedDisplay = false;
414 mParameters.associatedDisplayIsExternal = false;
415 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100416 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
417 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700418 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100419 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800420 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700421 std::string uniqueDisplayId;
422 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800423 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700424 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
425 }
426 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800427 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 mParameters.hasAssociatedDisplay = true;
429 }
430
431 // Initial downs on external touch devices should wake the device.
432 // Normally we don't do this for internal touch screens to prevent them from waking
433 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800434 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700435 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000436
437 mParameters.supportsUsi = false;
438 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
439 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700440
441 mParameters.enableForInactiveViewport = false;
442 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
443 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444}
445
446void TouchInputMapper::dumpParameters(std::string& dump) {
447 dump += INDENT3 "Parameters:\n";
448
Dominik Laskowski75788452021-02-09 18:51:25 -0800449 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450
Dominik Laskowski75788452021-02-09 18:51:25 -0800451 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452
453 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
454 "displayId='%s'\n",
455 toString(mParameters.hasAssociatedDisplay),
456 toString(mParameters.associatedDisplayIsExternal),
457 mParameters.uniqueDisplayId.c_str());
458 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800459 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000460 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700461 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
462 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463}
464
465void TouchInputMapper::configureRawPointerAxes() {
466 mRawPointerAxes.clear();
467}
468
469void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
470 dump += INDENT3 "Raw Touch Axes:\n";
471 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
472 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
473 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
474 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
475 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
476 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
477 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
478 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
479 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
480 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
481 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
482 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
483 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
484}
485
486bool TouchInputMapper::hasExternalStylus() const {
487 return mExternalStylusConnected;
488}
489
490/**
491 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000492 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800493 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000494 * 3. Get the matching viewport by either unique id in idc file or by the display type
495 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800496 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700497 */
498std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800499 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000500 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800501 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502 }
503
Christine Franks2a2293c2022-01-18 11:51:16 -0800504 const std::optional<std::string> associatedDisplayUniqueId =
505 getDeviceContext().getAssociatedDisplayUniqueId();
506 if (associatedDisplayUniqueId) {
507 return getDeviceContext().getAssociatedViewport();
508 }
509
Michael Wright227c5542020-07-02 18:30:52 +0100510 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800511 std::optional<DisplayViewport> viewport =
512 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
513 if (viewport) {
514 return viewport;
515 } else {
516 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
517 mConfig.defaultPointerDisplayId);
518 }
519 }
520
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700521 // Check if uniqueDisplayId is specified in idc file.
522 if (!mParameters.uniqueDisplayId.empty()) {
523 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
524 }
525
526 ViewportType viewportTypeToUse;
527 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100528 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700529 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100530 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700531 }
532
533 std::optional<DisplayViewport> viewport =
534 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100535 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700536 ALOGW("Input device %s should be associated with external display, "
537 "fallback to internal one for the external viewport is not found.",
538 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100539 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700540 }
541
542 return viewport;
543 }
544
545 // No associated display, return a non-display viewport.
546 DisplayViewport newViewport;
547 // Raw width and height in the natural orientation.
548 int32_t rawWidth = mRawPointerAxes.getRawWidth();
549 int32_t rawHeight = mRawPointerAxes.getRawHeight();
550 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
551 return std::make_optional(newViewport);
552}
553
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800554int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
555 if (resolution < 0) {
556 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
557 getDeviceName().c_str());
558 return 0;
559 }
560 return resolution;
561}
562
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800563void TouchInputMapper::initializeSizeRanges() {
564 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
565 mSizeScale = 0.0f;
566 return;
567 }
568
569 // Size of diagonal axis.
570 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
571
572 // Size factors.
573 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
574 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
575 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
576 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
577 } else {
578 mSizeScale = 0.0f;
579 }
580
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700581 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
582 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
583 .source = mSource,
584 .min = 0,
585 .max = diagonalSize,
586 .flat = 0,
587 .fuzz = 0,
588 .resolution = 0,
589 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800590
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800591 if (mRawPointerAxes.touchMajor.valid) {
592 mRawPointerAxes.touchMajor.resolution =
593 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700594 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800595 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800596
597 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700598 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800599 if (mRawPointerAxes.touchMinor.valid) {
600 mRawPointerAxes.touchMinor.resolution =
601 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700602 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800603 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800604
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700605 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
606 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
607 .source = mSource,
608 .min = 0,
609 .max = diagonalSize,
610 .flat = 0,
611 .fuzz = 0,
612 .resolution = 0,
613 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800614 if (mRawPointerAxes.toolMajor.valid) {
615 mRawPointerAxes.toolMajor.resolution =
616 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700617 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800618 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800619
620 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700621 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800622 if (mRawPointerAxes.toolMinor.valid) {
623 mRawPointerAxes.toolMinor.resolution =
624 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700625 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800626 }
627
628 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700629 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
630 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
631 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
632 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800633 } else {
634 // Support for other calibrations can be added here.
635 ALOGW("%s calibration is not supported for size ranges at the moment. "
636 "Using raw resolution instead",
637 ftl::enum_string(mCalibration.sizeCalibration).c_str());
638 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800639
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700640 mOrientedRanges.size = InputDeviceInfo::MotionRange{
641 .axis = AMOTION_EVENT_AXIS_SIZE,
642 .source = mSource,
643 .min = 0,
644 .max = 1.0,
645 .flat = 0,
646 .fuzz = 0,
647 .resolution = 0,
648 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800649}
650
651void TouchInputMapper::initializeOrientedRanges() {
652 // Configure X and Y factors.
653 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
654 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
655 mXPrecision = 1.0f / mXScale;
656 mYPrecision = 1.0f / mYScale;
657
658 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
659 mOrientedRanges.x.source = mSource;
660 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
661 mOrientedRanges.y.source = mSource;
662
663 // Scale factor for terms that are not oriented in a particular axis.
664 // If the pixels are square then xScale == yScale otherwise we fake it
665 // by choosing an average.
666 mGeometricScale = avg(mXScale, mYScale);
667
668 initializeSizeRanges();
669
670 // Pressure factors.
671 mPressureScale = 0;
672 float pressureMax = 1.0;
673 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
674 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700675 if (mCalibration.pressureScale) {
676 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800677 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
678 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
679 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
680 }
681 }
682
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700683 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
684 .axis = AMOTION_EVENT_AXIS_PRESSURE,
685 .source = mSource,
686 .min = 0,
687 .max = pressureMax,
688 .flat = 0,
689 .fuzz = 0,
690 .resolution = 0,
691 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800692
693 // Tilt
694 mTiltXCenter = 0;
695 mTiltXScale = 0;
696 mTiltYCenter = 0;
697 mTiltYScale = 0;
698 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
699 if (mHaveTilt) {
700 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
701 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
702 mTiltXScale = M_PI / 180;
703 mTiltYScale = M_PI / 180;
704
705 if (mRawPointerAxes.tiltX.resolution) {
706 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
707 }
708 if (mRawPointerAxes.tiltY.resolution) {
709 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
710 }
711
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700712 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
713 .axis = AMOTION_EVENT_AXIS_TILT,
714 .source = mSource,
715 .min = 0,
716 .max = M_PI_2,
717 .flat = 0,
718 .fuzz = 0,
719 .resolution = 0,
720 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800721 }
722
723 // Orientation
724 mOrientationScale = 0;
725 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700726 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
727 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
728 .source = mSource,
729 .min = -M_PI,
730 .max = M_PI,
731 .flat = 0,
732 .fuzz = 0,
733 .resolution = 0,
734 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800735
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800736 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
737 if (mCalibration.orientationCalibration ==
738 Calibration::OrientationCalibration::INTERPOLATED) {
739 if (mRawPointerAxes.orientation.valid) {
740 if (mRawPointerAxes.orientation.maxValue > 0) {
741 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
742 } else if (mRawPointerAxes.orientation.minValue < 0) {
743 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
744 } else {
745 mOrientationScale = 0;
746 }
747 }
748 }
749
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700750 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
751 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
752 .source = mSource,
753 .min = -M_PI_2,
754 .max = M_PI_2,
755 .flat = 0,
756 .fuzz = 0,
757 .resolution = 0,
758 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800759 }
760
761 // Distance
762 mDistanceScale = 0;
763 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
764 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700765 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800766 }
767
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700768 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800769
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700770 .axis = AMOTION_EVENT_AXIS_DISTANCE,
771 .source = mSource,
772 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
773 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
774 .flat = 0,
775 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
776 .resolution = 0,
777 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800778 }
779
780 // Compute oriented precision, scales and ranges.
781 // Note that the maximum value reported is an inclusive maximum value so it is one
782 // unit less than the total width or height of the display.
783 switch (mInputDeviceOrientation) {
784 case DISPLAY_ORIENTATION_90:
785 case DISPLAY_ORIENTATION_270:
786 mOrientedXPrecision = mYPrecision;
787 mOrientedYPrecision = mXPrecision;
788
789 mOrientedRanges.x.min = 0;
790 mOrientedRanges.x.max = mDisplayHeight - 1;
791 mOrientedRanges.x.flat = 0;
792 mOrientedRanges.x.fuzz = 0;
793 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
794
795 mOrientedRanges.y.min = 0;
796 mOrientedRanges.y.max = mDisplayWidth - 1;
797 mOrientedRanges.y.flat = 0;
798 mOrientedRanges.y.fuzz = 0;
799 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
800 break;
801
802 default:
803 mOrientedXPrecision = mXPrecision;
804 mOrientedYPrecision = mYPrecision;
805
806 mOrientedRanges.x.min = 0;
807 mOrientedRanges.x.max = mDisplayWidth - 1;
808 mOrientedRanges.x.flat = 0;
809 mOrientedRanges.x.fuzz = 0;
810 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
811
812 mOrientedRanges.y.min = 0;
813 mOrientedRanges.y.max = mDisplayHeight - 1;
814 mOrientedRanges.y.flat = 0;
815 mOrientedRanges.y.fuzz = 0;
816 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
817 break;
818 }
819}
820
Prabir Pradhan1728b212021-10-19 16:00:03 -0700821void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000822 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700823
824 resolveExternalStylusPresence();
825
826 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100827 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000828 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700829 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100830 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700831 if (hasStylus()) {
832 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000833 } else {
834 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700835 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800836 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700837 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100838 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700839 if (hasStylus()) {
840 mSource |= AINPUT_SOURCE_STYLUS;
841 }
842 if (hasExternalStylus()) {
843 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
844 }
Michael Wright227c5542020-07-02 18:30:52 +0100845 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700846 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100847 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700848 } else {
849 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100850 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700851 }
852
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000853 const std::optional<DisplayViewport> newViewportOpt = findViewport();
854
855 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700856 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
857 ALOGW("Touch device '%s' did not report support for X or Y axis! "
858 "The device will be inoperable.",
859 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100860 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000861 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700862 ALOGI("Touch device '%s' could not query the properties of its associated "
863 "display. The device will be inoperable until the display size "
864 "becomes available.",
865 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100866 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700867 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000868 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
869 getDeviceName().c_str(), getDeviceId());
870 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000871 }
872
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700873 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700874 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
875 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000876 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
877 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
878 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
879 const float rawMeanResolution =
880 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700881
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000882 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
883 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700884 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700885 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000886 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
887 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
888 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700889
Michael Wright227c5542020-07-02 18:30:52 +0100890 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700891 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700892 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
893 int32_t naturalPhysicalLeft, naturalPhysicalTop;
894 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700895
Prabir Pradhan1728b212021-10-19 16:00:03 -0700896 // Apply the inverse of the input device orientation so that the input device is
897 // configured in the same orientation as the viewport. The input device orientation will
898 // be re-applied by mInputDeviceOrientation.
899 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700900 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700901 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
904 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800905 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700906 naturalPhysicalTop = mViewport.physicalLeft;
907 naturalDeviceWidth = mViewport.deviceHeight;
908 naturalDeviceHeight = mViewport.deviceWidth;
909 break;
910 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
912 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
913 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
914 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
915 naturalDeviceWidth = mViewport.deviceWidth;
916 naturalDeviceHeight = mViewport.deviceHeight;
917 break;
918 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700919 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
920 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
921 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800922 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700923 naturalDeviceWidth = mViewport.deviceHeight;
924 naturalDeviceHeight = mViewport.deviceWidth;
925 break;
926 case DISPLAY_ORIENTATION_0:
927 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700928 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
929 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
930 naturalPhysicalLeft = mViewport.physicalLeft;
931 naturalPhysicalTop = mViewport.physicalTop;
932 naturalDeviceWidth = mViewport.deviceWidth;
933 naturalDeviceHeight = mViewport.deviceHeight;
934 break;
935 }
936
937 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
938 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
939 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
940 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
941 }
942
943 mPhysicalWidth = naturalPhysicalWidth;
944 mPhysicalHeight = naturalPhysicalHeight;
945 mPhysicalLeft = naturalPhysicalLeft;
946 mPhysicalTop = naturalPhysicalTop;
947
Prabir Pradhan1728b212021-10-19 16:00:03 -0700948 const int32_t oldDisplayWidth = mDisplayWidth;
949 const int32_t oldDisplayHeight = mDisplayHeight;
950 mDisplayWidth = naturalDeviceWidth;
951 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700952
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000953 // InputReader works in the un-rotated display coordinate space, so we don't need to do
954 // anything if the device is already orientation-aware. If the device is not
955 // orientation-aware, then we need to apply the inverse rotation of the display so that
956 // when the display rotation is applied later as a part of the per-window transform, we
957 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700958 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000959 ? DISPLAY_ORIENTATION_0
960 : getInverseRotation(mViewport.orientation);
961 // For orientation-aware devices that work in the un-rotated coordinate space, the
962 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000963 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
964 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
965 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700966
967 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700968 mInputDeviceOrientation =
969 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700970 } else {
971 mPhysicalWidth = rawWidth;
972 mPhysicalHeight = rawHeight;
973 mPhysicalLeft = 0;
974 mPhysicalTop = 0;
975
Prabir Pradhan1728b212021-10-19 16:00:03 -0700976 mDisplayWidth = rawWidth;
977 mDisplayHeight = rawHeight;
978 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700979 }
980 }
981
982 // If moving between pointer modes, need to reset some state.
983 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
984 if (deviceModeChanged) {
985 mOrientedRanges.clear();
986 }
987
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800988 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
989 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100990 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800991 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000992 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
993 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800994 if (mPointerController == nullptr) {
995 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000997 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800998 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
999 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001000 } else {
lilinnandef700b2022-06-17 19:32:01 +08001001 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1002 !mConfig.showTouches) {
1003 mPointerController->clearSpots();
1004 }
Michael Wright17db18e2020-06-26 20:51:44 +01001005 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001006 }
1007
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001008 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001009 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1010 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001011 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1012 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001013
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001014 configureVirtualKeys();
1015
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001016 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001017
1018 // Location
1019 updateAffineTransformation();
1020
Michael Wright227c5542020-07-02 18:30:52 +01001021 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001022 // Compute pointer gesture detection parameters.
1023 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001024 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001025
1026 // Scale movements such that one whole swipe of the touch pad covers a
1027 // given area relative to the diagonal size of the display when no acceleration
1028 // is applied.
1029 // Assume that the touch pad has a square aspect ratio such that movements in
1030 // X and Y of the same number of raw units cover the same physical distance.
1031 mPointerXMovementScale =
1032 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1033 mPointerYMovementScale = mPointerXMovementScale;
1034
1035 // Scale zooms to cover a smaller range of the display than movements do.
1036 // This value determines the area around the pointer that is affected by freeform
1037 // pointer gestures.
1038 mPointerXZoomScale =
1039 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1040 mPointerYZoomScale = mPointerXZoomScale;
1041
HQ Liue6983c72022-04-19 22:14:56 +00001042 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1043 // axis is non positive value.
1044 const float minFreeformGestureWidth =
1045 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1046
1047 mPointerGestureMaxSwipeWidth =
1048 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1049 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001050 }
1051
1052 // Inform the dispatcher about the changes.
1053 *outResetNeeded = true;
1054 bumpGeneration();
1055 }
1056}
1057
Prabir Pradhan1728b212021-10-19 16:00:03 -07001058void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001060 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1061 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1063 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1064 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1065 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001066 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067}
1068
1069void TouchInputMapper::configureVirtualKeys() {
1070 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001071 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001072
1073 mVirtualKeys.clear();
1074
1075 if (virtualKeyDefinitions.size() == 0) {
1076 return;
1077 }
1078
1079 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1080 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1081 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1082 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1083
1084 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1085 VirtualKey virtualKey;
1086
1087 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1088 int32_t keyCode;
1089 int32_t dummyKeyMetaState;
1090 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001091 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1092 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001093 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1094 continue; // drop the key
1095 }
1096
1097 virtualKey.keyCode = keyCode;
1098 virtualKey.flags = flags;
1099
1100 // convert the key definition's display coordinates into touch coordinates for a hit box
1101 int32_t halfWidth = virtualKeyDefinition.width / 2;
1102 int32_t halfHeight = virtualKeyDefinition.height / 2;
1103
1104 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001105 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001106 touchScreenLeft;
1107 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001108 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001110 virtualKey.hitTop =
1111 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001113 virtualKey.hitBottom =
1114 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001115 touchScreenTop;
1116 mVirtualKeys.push_back(virtualKey);
1117 }
1118}
1119
1120void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1121 if (!mVirtualKeys.empty()) {
1122 dump += INDENT3 "Virtual Keys:\n";
1123
1124 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1125 const VirtualKey& virtualKey = mVirtualKeys[i];
1126 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1127 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1128 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1129 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1130 }
1131 }
1132}
1133
1134void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001135 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 Calibration& out = mCalibration;
1137
1138 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001139 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001140 std::string sizeCalibrationString;
1141 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001145 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001147 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001149 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001151 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001152 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001153 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 }
1155 }
1156
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001157 float sizeScale;
1158
1159 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1160 out.sizeScale = sizeScale;
1161 }
1162 float sizeBias;
1163 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1164 out.sizeBias = sizeBias;
1165 }
1166 bool sizeIsSummed;
1167 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1168 out.sizeIsSummed = sizeIsSummed;
1169 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170
1171 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001172 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001173 std::string pressureCalibrationString;
1174 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001176 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001178 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001180 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 } else if (pressureCalibrationString != "default") {
1182 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001183 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 }
1185 }
1186
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001187 float pressureScale;
1188 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1189 out.pressureScale = pressureScale;
1190 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191
1192 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001193 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001194 std::string orientationCalibrationString;
1195 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 } else if (orientationCalibrationString != "default") {
1203 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001204 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 }
1206 }
1207
1208 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001210 std::string distanceCalibrationString;
1211 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001215 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 } else if (distanceCalibrationString != "default") {
1217 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001218 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 }
1220 }
1221
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001222 float distanceScale;
1223 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1224 out.distanceScale = distanceScale;
1225 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226
Michael Wright227c5542020-07-02 18:30:52 +01001227 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001228 std::string coverageCalibrationString;
1229 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001231 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001233 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 } else if (coverageCalibrationString != "default") {
1235 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001236 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238 }
1239}
1240
1241void TouchInputMapper::resolveCalibration() {
1242 // Size
1243 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001244 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1245 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001248 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250
1251 // Pressure
1252 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001253 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1254 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001257 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
1259
1260 // Orientation
1261 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001262 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1263 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001266 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 }
1268
1269 // Distance
1270 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001271 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1272 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 }
1274 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001275 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 }
1277
1278 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001279 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1280 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 }
1282}
1283
1284void TouchInputMapper::dumpCalibration(std::string& dump) {
1285 dump += INDENT3 "Calibration:\n";
1286
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001287 dump += INDENT4 "touch.size.calibration: ";
1288 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001290 if (mCalibration.sizeScale) {
1291 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 }
1293
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001294 if (mCalibration.sizeBias) {
1295 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 }
1297
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001298 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001300 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 }
1302
1303 // Pressure
1304 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001305 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 dump += INDENT4 "touch.pressure.calibration: none\n";
1307 break;
Michael Wright227c5542020-07-02 18:30:52 +01001308 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 dump += INDENT4 "touch.pressure.calibration: physical\n";
1310 break;
Michael Wright227c5542020-07-02 18:30:52 +01001311 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1313 break;
1314 default:
1315 ALOG_ASSERT(false);
1316 }
1317
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001318 if (mCalibration.pressureScale) {
1319 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 }
1321
1322 // Orientation
1323 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001324 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.orientation.calibration: none\n";
1326 break;
Michael Wright227c5542020-07-02 18:30:52 +01001327 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1329 break;
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.orientation.calibration: vector\n";
1332 break;
1333 default:
1334 ALOG_ASSERT(false);
1335 }
1336
1337 // Distance
1338 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001339 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340 dump += INDENT4 "touch.distance.calibration: none\n";
1341 break;
Michael Wright227c5542020-07-02 18:30:52 +01001342 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 dump += INDENT4 "touch.distance.calibration: scaled\n";
1344 break;
1345 default:
1346 ALOG_ASSERT(false);
1347 }
1348
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001349 if (mCalibration.distanceScale) {
1350 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001351 }
1352
1353 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001354 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001355 dump += INDENT4 "touch.coverage.calibration: none\n";
1356 break;
Michael Wright227c5542020-07-02 18:30:52 +01001357 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001358 dump += INDENT4 "touch.coverage.calibration: box\n";
1359 break;
1360 default:
1361 ALOG_ASSERT(false);
1362 }
1363}
1364
1365void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1366 dump += INDENT3 "Affine Transformation:\n";
1367
1368 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1369 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1370 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1371 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1372 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1373 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1374}
1375
1376void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001377 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001378 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379}
1380
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001381std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001382 std::list<NotifyArgs> out = cancelTouch(when, when);
1383 updateTouchSpots();
1384
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001385 mCursorButtonAccumulator.reset(getDeviceContext());
1386 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001387 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001388
1389 mPointerVelocityControl.reset();
1390 mWheelXVelocityControl.reset();
1391 mWheelYVelocityControl.reset();
1392
1393 mRawStatesPending.clear();
1394 mCurrentRawState.clear();
1395 mCurrentCookedState.clear();
1396 mLastRawState.clear();
1397 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001398 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001399 mSentHoverEnter = false;
1400 mHavePointerIds = false;
1401 mCurrentMotionAborted = false;
1402 mDownTime = 0;
1403
1404 mCurrentVirtualKey.down = false;
1405
1406 mPointerGesture.reset();
1407 mPointerSimple.reset();
1408 resetExternalStylus();
1409
1410 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001411 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001412 mPointerController->clearSpots();
1413 }
1414
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001415 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001416}
1417
1418void TouchInputMapper::resetExternalStylus() {
1419 mExternalStylusState.clear();
1420 mExternalStylusId = -1;
1421 mExternalStylusFusionTimeout = LLONG_MAX;
1422 mExternalStylusDataPending = false;
1423}
1424
1425void TouchInputMapper::clearStylusDataPendingFlags() {
1426 mExternalStylusDataPending = false;
1427 mExternalStylusFusionTimeout = LLONG_MAX;
1428}
1429
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001430std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431 mCursorButtonAccumulator.process(rawEvent);
1432 mCursorScrollAccumulator.process(rawEvent);
1433 mTouchButtonAccumulator.process(rawEvent);
1434
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001435 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001437 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001439 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440}
1441
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001442std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1443 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001444 if (mDeviceMode == DeviceMode::DISABLED) {
1445 // Only save the last pending state when the device is disabled.
1446 mRawStatesPending.clear();
1447 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001448 // Push a new state.
1449 mRawStatesPending.emplace_back();
1450
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001451 RawState& next = mRawStatesPending.back();
1452 next.clear();
1453 next.when = when;
1454 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455
1456 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001457 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001458 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1459
1460 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001461 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1462 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001463 mCursorScrollAccumulator.finishSync();
1464
1465 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001466 syncTouch(when, &next);
1467
1468 // The last RawState is the actually second to last, since we just added a new state
1469 const RawState& last =
1470 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001471
1472 // Assign pointer ids.
1473 if (!mHavePointerIds) {
1474 assignPointerIds(last, next);
1475 }
1476
Harry Cutts45483602022-08-24 14:36:48 +00001477 ALOGD_IF(DEBUG_RAW_EVENTS,
1478 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1479 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1480 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1481 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1482 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1483 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001484
Arthur Hung9ad18942021-06-19 02:04:46 +00001485 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1486 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1487 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1488 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1489 next.rawPointerData.hoveringIdBits.value);
1490 }
1491
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001492 out += processRawTouches(false /*timeout*/);
1493 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001494}
1495
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001496std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1497 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001498 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001499 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001500 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001501 }
1502
1503 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1504 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1505 // touching the current state will only observe the events that have been dispatched to the
1506 // rest of the pipeline.
1507 const size_t N = mRawStatesPending.size();
1508 size_t count;
1509 for (count = 0; count < N; count++) {
1510 const RawState& next = mRawStatesPending[count];
1511
1512 // A failure to assign the stylus id means that we're waiting on stylus data
1513 // and so should defer the rest of the pipeline.
1514 if (assignExternalStylusId(next, timeout)) {
1515 break;
1516 }
1517
1518 // All ready to go.
1519 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001520 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521 if (mCurrentRawState.when < mLastRawState.when) {
1522 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001523 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001525 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001526 }
1527 if (count != 0) {
1528 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1529 }
1530
1531 if (mExternalStylusDataPending) {
1532 if (timeout) {
1533 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1534 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001535 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001536 ALOGD_IF(DEBUG_STYLUS_FUSION,
1537 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001538 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001539 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001540 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1541 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1542 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1543 }
1544 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001545 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001546}
1547
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001548std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1549 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550 // Always start with a clean state.
1551 mCurrentCookedState.clear();
1552
1553 // Apply stylus buttons to current raw state.
1554 applyExternalStylusButtonState(when);
1555
1556 // Handle policy on initial down or hover events.
1557 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1558 mCurrentRawState.rawPointerData.pointerCount != 0;
1559
1560 uint32_t policyFlags = 0;
1561 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1562 if (initialDown || buttonsPressed) {
1563 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001564 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001565 getContext()->fadePointer();
1566 }
1567
1568 if (mParameters.wake) {
1569 policyFlags |= POLICY_FLAG_WAKE;
1570 }
1571 }
1572
1573 // Consume raw off-screen touches before cooking pointer data.
1574 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001575 bool consumed;
1576 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1577 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001578 mCurrentRawState.rawPointerData.clear();
1579 }
1580
1581 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1582 // with cooked pointer data that has the same ids and indices as the raw data.
1583 // The following code can use either the raw or cooked data, as needed.
1584 cookPointerData();
1585
1586 // Apply stylus pressure to current cooked state.
1587 applyExternalStylusTouchState(when);
1588
1589 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001590 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1591 mSource, mViewport.displayId, policyFlags,
1592 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001593
1594 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001595 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1597 uint32_t id = idBits.clearFirstMarkedBit();
1598 const RawPointerData::Pointer& pointer =
1599 mCurrentRawState.rawPointerData.pointerForId(id);
1600 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1601 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1602 mCurrentCookedState.stylusIdBits.markBit(id);
1603 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1604 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1605 mCurrentCookedState.fingerIdBits.markBit(id);
1606 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1607 mCurrentCookedState.mouseIdBits.markBit(id);
1608 }
1609 }
1610 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1611 uint32_t id = idBits.clearFirstMarkedBit();
1612 const RawPointerData::Pointer& pointer =
1613 mCurrentRawState.rawPointerData.pointerForId(id);
1614 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1615 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1616 mCurrentCookedState.stylusIdBits.markBit(id);
1617 }
1618 }
1619
1620 // Stylus takes precedence over all tools, then mouse, then finger.
1621 PointerUsage pointerUsage = mPointerUsage;
1622 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1623 mCurrentCookedState.mouseIdBits.clear();
1624 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001625 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1627 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001628 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1630 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001631 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 }
1633
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001634 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001635 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001637 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001638 out += dispatchButtonRelease(when, readTime, policyFlags);
1639 out += dispatchHoverExit(when, readTime, policyFlags);
1640 out += dispatchTouches(when, readTime, policyFlags);
1641 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1642 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001643 }
1644
1645 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1646 mCurrentMotionAborted = false;
1647 }
1648 }
1649
1650 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001651 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1652 mSource, mViewport.displayId, policyFlags,
1653 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001654
1655 // Clear some transient state.
1656 mCurrentRawState.rawVScroll = 0;
1657 mCurrentRawState.rawHScroll = 0;
1658
1659 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001660 mLastRawState = mCurrentRawState;
1661 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001662 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001663}
1664
Garfield Tanc734e4f2021-01-15 20:01:39 -08001665void TouchInputMapper::updateTouchSpots() {
1666 if (!mConfig.showTouches || mPointerController == nullptr) {
1667 return;
1668 }
1669
1670 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1671 // clear touch spots.
1672 if (mDeviceMode != DeviceMode::DIRECT &&
1673 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1674 return;
1675 }
1676
1677 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1678 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1679
1680 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001681 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1682 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001683 mCurrentCookedState.cookedPointerData.touchingIdBits,
1684 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001685}
1686
1687bool TouchInputMapper::isTouchScreen() {
1688 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1689 mParameters.hasAssociatedDisplay;
1690}
1691
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001692void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001693 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001694 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1695 }
1696}
1697
1698void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1699 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1700 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1701
1702 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1703 float pressure = mExternalStylusState.pressure;
1704 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1705 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1706 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1707 }
1708 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1709 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1710
1711 PointerProperties& properties =
1712 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1713 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1714 properties.toolType = mExternalStylusState.toolType;
1715 }
1716 }
1717}
1718
1719bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001720 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001721 return false;
1722 }
1723
1724 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1725 state.rawPointerData.pointerCount != 0;
1726 if (initialDown) {
1727 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001728 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001729 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1730 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001731 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001732 resetExternalStylus();
1733 } else {
1734 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1735 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1736 }
Harry Cutts45483602022-08-24 14:36:48 +00001737 ALOGD_IF(DEBUG_STYLUS_FUSION,
1738 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1739 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001740 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1741 return true;
1742 }
1743 }
1744
1745 // Check if the stylus pointer has gone up.
1746 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001747 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001748 mExternalStylusId = -1;
1749 }
1750
1751 return false;
1752}
1753
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001754std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1755 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001756 if (mDeviceMode == DeviceMode::POINTER) {
1757 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001758 // Since this is a synthetic event, we can consider its latency to be zero
1759 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001760 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001761 }
Michael Wright227c5542020-07-02 18:30:52 +01001762 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001763 if (mExternalStylusFusionTimeout < when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001764 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001765 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1766 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1767 }
1768 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001769 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001770}
1771
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001772std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1773 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001774 mExternalStylusState.copyFrom(state);
1775 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1776 // We're either in the middle of a fused stream of data or we're waiting on data before
1777 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1778 // data.
1779 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001780 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001781 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001782 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001783}
1784
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001785std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1786 uint32_t policyFlags, bool& outConsumed) {
1787 outConsumed = false;
1788 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001789 // Check for release of a virtual key.
1790 if (mCurrentVirtualKey.down) {
1791 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1792 // Pointer went up while virtual key was down.
1793 mCurrentVirtualKey.down = false;
1794 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001795 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1796 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1797 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001798 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1799 AKEY_EVENT_FLAG_FROM_SYSTEM |
1800 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001801 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001802 outConsumed = true;
1803 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001804 }
1805
1806 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1807 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1808 const RawPointerData::Pointer& pointer =
1809 mCurrentRawState.rawPointerData.pointerForId(id);
1810 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1811 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1812 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001813 outConsumed = true;
1814 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001815 }
1816 }
1817
1818 // Pointer left virtual key area or another pointer also went down.
1819 // Send key cancellation but do not consume the touch yet.
1820 // This is useful when the user swipes through from the virtual key area
1821 // into the main display surface.
1822 mCurrentVirtualKey.down = false;
1823 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001824 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1825 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001826 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1827 AKEY_EVENT_FLAG_FROM_SYSTEM |
1828 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1829 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001830 }
1831 }
1832
1833 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1834 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1835 // Pointer just went down. Check for virtual key press or off-screen touches.
1836 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1837 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001838 // Skip checking whether the pointer is inside the physical frame if the device is in
1839 // unscaled mode.
1840 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1841 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001842 // If exactly one pointer went down, check for virtual key hit.
1843 // Otherwise we will drop the entire stroke.
1844 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1845 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1846 if (virtualKey) {
1847 mCurrentVirtualKey.down = true;
1848 mCurrentVirtualKey.downTime = when;
1849 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1850 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1851 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001852 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1853 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854
1855 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001856 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1857 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1858 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001859 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1860 AKEY_EVENT_ACTION_DOWN,
1861 AKEY_EVENT_FLAG_FROM_SYSTEM |
1862 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001863 }
1864 }
1865 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001866 outConsumed = true;
1867 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001868 }
1869 }
1870
1871 // Disable all virtual key touches that happen within a short time interval of the
1872 // most recent touch within the screen area. The idea is to filter out stray
1873 // virtual key presses when interacting with the touch screen.
1874 //
1875 // Problems we're trying to solve:
1876 //
1877 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1878 // virtual key area that is implemented by a separate touch panel and accidentally
1879 // triggers a virtual key.
1880 //
1881 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1882 // area and accidentally triggers a virtual key. This often happens when virtual keys
1883 // are layed out below the screen near to where the on screen keyboard's space bar
1884 // is displayed.
1885 if (mConfig.virtualKeyQuietTime > 0 &&
1886 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001887 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001888 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001889 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001890}
1891
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001892NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1893 uint32_t policyFlags, int32_t keyEventAction,
1894 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001895 int32_t keyCode = mCurrentVirtualKey.keyCode;
1896 int32_t scanCode = mCurrentVirtualKey.scanCode;
1897 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001898 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001899 policyFlags |= POLICY_FLAG_VIRTUAL;
1900
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001901 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1902 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1903 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001904}
1905
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001906std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1907 uint32_t policyFlags) {
1908 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001909 if (mCurrentMotionAborted) {
1910 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001911 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001912 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001913 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1914 if (!currentIdBits.isEmpty()) {
1915 int32_t metaState = getContext()->getGlobalMetaState();
1916 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001917 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001918 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1919 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 mCurrentCookedState.cookedPointerData.pointerProperties,
1921 mCurrentCookedState.cookedPointerData.pointerCoords,
1922 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1923 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1924 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001925 mCurrentMotionAborted = true;
1926 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001927 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001928}
1929
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001930// Updates pointer coords and properties for pointers with specified ids that have moved.
1931// Returns true if any of them changed.
1932static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1933 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1934 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1935 BitSet32 idBits) {
1936 bool changed = false;
1937 while (!idBits.isEmpty()) {
1938 uint32_t id = idBits.clearFirstMarkedBit();
1939 uint32_t inIndex = inIdToIndex[id];
1940 uint32_t outIndex = outIdToIndex[id];
1941
1942 const PointerProperties& curInProperties = inProperties[inIndex];
1943 const PointerCoords& curInCoords = inCoords[inIndex];
1944 PointerProperties& curOutProperties = outProperties[outIndex];
1945 PointerCoords& curOutCoords = outCoords[outIndex];
1946
1947 if (curInProperties != curOutProperties) {
1948 curOutProperties.copyFrom(curInProperties);
1949 changed = true;
1950 }
1951
1952 if (curInCoords != curOutCoords) {
1953 curOutCoords.copyFrom(curInCoords);
1954 changed = true;
1955 }
1956 }
1957 return changed;
1958}
1959
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001960std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1961 uint32_t policyFlags) {
1962 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001963 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1964 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1965 int32_t metaState = getContext()->getGlobalMetaState();
1966 int32_t buttonState = mCurrentCookedState.buttonState;
1967
1968 if (currentIdBits == lastIdBits) {
1969 if (!currentIdBits.isEmpty()) {
1970 // No pointer id changes so this is a move event.
1971 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001972 out.push_back(
1973 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1974 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1975 mCurrentCookedState.cookedPointerData.pointerProperties,
1976 mCurrentCookedState.cookedPointerData.pointerCoords,
1977 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1978 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1979 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001980 }
1981 } else {
1982 // There may be pointers going up and pointers going down and pointers moving
1983 // all at the same time.
1984 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1985 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1986 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1987 BitSet32 dispatchedIdBits(lastIdBits.value);
1988
1989 // Update last coordinates of pointers that have moved so that we observe the new
1990 // pointer positions at the same time as other pointers that have just gone up.
1991 bool moveNeeded =
1992 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1993 mCurrentCookedState.cookedPointerData.pointerCoords,
1994 mCurrentCookedState.cookedPointerData.idToIndex,
1995 mLastCookedState.cookedPointerData.pointerProperties,
1996 mLastCookedState.cookedPointerData.pointerCoords,
1997 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1998 if (buttonState != mLastCookedState.buttonState) {
1999 moveNeeded = true;
2000 }
2001
2002 // Dispatch pointer up events.
2003 while (!upIdBits.isEmpty()) {
2004 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002005 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002006 if (isCanceled) {
2007 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2008 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002009 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2010 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2011 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2012 buttonState, 0,
2013 mLastCookedState.cookedPointerData.pointerProperties,
2014 mLastCookedState.cookedPointerData.pointerCoords,
2015 mLastCookedState.cookedPointerData.idToIndex,
2016 dispatchedIdBits, upId, mOrientedXPrecision,
2017 mOrientedYPrecision, mDownTime,
2018 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002019 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002020 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002021 }
2022
2023 // Dispatch move events if any of the remaining pointers moved from their old locations.
2024 // Although applications receive new locations as part of individual pointer up
2025 // events, they do not generally handle them except when presented in a move event.
2026 if (moveNeeded && !moveIdBits.isEmpty()) {
2027 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002028 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2029 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2030 mCurrentCookedState.cookedPointerData.pointerProperties,
2031 mCurrentCookedState.cookedPointerData.pointerCoords,
2032 mCurrentCookedState.cookedPointerData.idToIndex,
2033 dispatchedIdBits, -1, mOrientedXPrecision,
2034 mOrientedYPrecision, mDownTime,
2035 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002036 }
2037
2038 // Dispatch pointer down events using the new pointer locations.
2039 while (!downIdBits.isEmpty()) {
2040 uint32_t downId = downIdBits.clearFirstMarkedBit();
2041 dispatchedIdBits.markBit(downId);
2042
2043 if (dispatchedIdBits.count() == 1) {
2044 // First pointer is going down. Set down time.
2045 mDownTime = when;
2046 }
2047
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002048 out.push_back(
2049 dispatchMotion(when, readTime, policyFlags, mSource,
2050 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2051 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2052 mCurrentCookedState.cookedPointerData.pointerCoords,
2053 mCurrentCookedState.cookedPointerData.idToIndex,
2054 dispatchedIdBits, downId, mOrientedXPrecision,
2055 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002056 }
2057 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002058 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002059}
2060
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002061std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2062 uint32_t policyFlags) {
2063 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002064 if (mSentHoverEnter &&
2065 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2066 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2067 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002068 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2069 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2070 mLastCookedState.buttonState, 0,
2071 mLastCookedState.cookedPointerData.pointerProperties,
2072 mLastCookedState.cookedPointerData.pointerCoords,
2073 mLastCookedState.cookedPointerData.idToIndex,
2074 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2075 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2076 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002077 mSentHoverEnter = false;
2078 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002079 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002080}
2081
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002082std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2083 uint32_t policyFlags) {
2084 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002085 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2086 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2087 int32_t metaState = getContext()->getGlobalMetaState();
2088 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002089 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2090 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2091 mCurrentRawState.buttonState, 0,
2092 mCurrentCookedState.cookedPointerData.pointerProperties,
2093 mCurrentCookedState.cookedPointerData.pointerCoords,
2094 mCurrentCookedState.cookedPointerData.idToIndex,
2095 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2096 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2097 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002098 mSentHoverEnter = true;
2099 }
2100
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002101 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2102 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2103 mCurrentRawState.buttonState, 0,
2104 mCurrentCookedState.cookedPointerData.pointerProperties,
2105 mCurrentCookedState.cookedPointerData.pointerCoords,
2106 mCurrentCookedState.cookedPointerData.idToIndex,
2107 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2108 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2109 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002111 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002112}
2113
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002114std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2115 uint32_t policyFlags) {
2116 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002117 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2118 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2119 const int32_t metaState = getContext()->getGlobalMetaState();
2120 int32_t buttonState = mLastCookedState.buttonState;
2121 while (!releasedButtons.isEmpty()) {
2122 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2123 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002124 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2125 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2126 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002127 mLastCookedState.cookedPointerData.pointerProperties,
2128 mLastCookedState.cookedPointerData.pointerCoords,
2129 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002130 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2131 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002132 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002133 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002134}
2135
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002136std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2137 uint32_t policyFlags) {
2138 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002139 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2140 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2141 const int32_t metaState = getContext()->getGlobalMetaState();
2142 int32_t buttonState = mLastCookedState.buttonState;
2143 while (!pressedButtons.isEmpty()) {
2144 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2145 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002146 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2147 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2148 buttonState, 0,
2149 mCurrentCookedState.cookedPointerData.pointerProperties,
2150 mCurrentCookedState.cookedPointerData.pointerCoords,
2151 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2152 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2153 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002155 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002156}
2157
2158const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2159 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2160 return cookedPointerData.touchingIdBits;
2161 }
2162 return cookedPointerData.hoveringIdBits;
2163}
2164
2165void TouchInputMapper::cookPointerData() {
2166 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2167
2168 mCurrentCookedState.cookedPointerData.clear();
2169 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2170 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2171 mCurrentRawState.rawPointerData.hoveringIdBits;
2172 mCurrentCookedState.cookedPointerData.touchingIdBits =
2173 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002174 mCurrentCookedState.cookedPointerData.canceledIdBits =
2175 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002176
2177 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2178 mCurrentCookedState.buttonState = 0;
2179 } else {
2180 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2181 }
2182
2183 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002184 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185 for (uint32_t i = 0; i < currentPointerCount; i++) {
2186 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2187
2188 // Size
2189 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2190 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002191 case Calibration::SizeCalibration::GEOMETRIC:
2192 case Calibration::SizeCalibration::DIAMETER:
2193 case Calibration::SizeCalibration::BOX:
2194 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002195 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2196 touchMajor = in.touchMajor;
2197 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2198 toolMajor = in.toolMajor;
2199 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2200 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2201 : in.touchMajor;
2202 } else if (mRawPointerAxes.touchMajor.valid) {
2203 toolMajor = touchMajor = in.touchMajor;
2204 toolMinor = touchMinor =
2205 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2206 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2207 : in.touchMajor;
2208 } else if (mRawPointerAxes.toolMajor.valid) {
2209 touchMajor = toolMajor = in.toolMajor;
2210 touchMinor = toolMinor =
2211 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2212 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2213 : in.toolMajor;
2214 } else {
2215 ALOG_ASSERT(false,
2216 "No touch or tool axes. "
2217 "Size calibration should have been resolved to NONE.");
2218 touchMajor = 0;
2219 touchMinor = 0;
2220 toolMajor = 0;
2221 toolMinor = 0;
2222 size = 0;
2223 }
2224
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002225 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002226 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2227 if (touchingCount > 1) {
2228 touchMajor /= touchingCount;
2229 touchMinor /= touchingCount;
2230 toolMajor /= touchingCount;
2231 toolMinor /= touchingCount;
2232 size /= touchingCount;
2233 }
2234 }
2235
Michael Wright227c5542020-07-02 18:30:52 +01002236 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002237 touchMajor *= mGeometricScale;
2238 touchMinor *= mGeometricScale;
2239 toolMajor *= mGeometricScale;
2240 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002241 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002242 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2243 touchMinor = touchMajor;
2244 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2245 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002246 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002247 touchMinor = touchMajor;
2248 toolMinor = toolMajor;
2249 }
2250
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002251 mCalibration.applySizeScaleAndBias(touchMajor);
2252 mCalibration.applySizeScaleAndBias(touchMinor);
2253 mCalibration.applySizeScaleAndBias(toolMajor);
2254 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002255 size *= mSizeScale;
2256 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002257 case Calibration::SizeCalibration::DEFAULT:
2258 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2259 break;
2260 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002261 touchMajor = 0;
2262 touchMinor = 0;
2263 toolMajor = 0;
2264 toolMinor = 0;
2265 size = 0;
2266 break;
2267 }
2268
2269 // Pressure
2270 float pressure;
2271 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002272 case Calibration::PressureCalibration::PHYSICAL:
2273 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002274 pressure = in.pressure * mPressureScale;
2275 break;
2276 default:
2277 pressure = in.isHovering ? 0 : 1;
2278 break;
2279 }
2280
2281 // Tilt and Orientation
2282 float tilt;
2283 float orientation;
2284 if (mHaveTilt) {
2285 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2286 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2287 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2288 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2289 } else {
2290 tilt = 0;
2291
2292 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002293 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002294 orientation = in.orientation * mOrientationScale;
2295 break;
Michael Wright227c5542020-07-02 18:30:52 +01002296 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2298 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2299 if (c1 != 0 || c2 != 0) {
2300 orientation = atan2f(c1, c2) * 0.5f;
2301 float confidence = hypotf(c1, c2);
2302 float scale = 1.0f + confidence / 16.0f;
2303 touchMajor *= scale;
2304 touchMinor /= scale;
2305 toolMajor *= scale;
2306 toolMinor /= scale;
2307 } else {
2308 orientation = 0;
2309 }
2310 break;
2311 }
2312 default:
2313 orientation = 0;
2314 }
2315 }
2316
2317 // Distance
2318 float distance;
2319 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002320 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002321 distance = in.distance * mDistanceScale;
2322 break;
2323 default:
2324 distance = 0;
2325 }
2326
2327 // Coverage
2328 int32_t rawLeft, rawTop, rawRight, rawBottom;
2329 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002330 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002331 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2332 rawRight = in.toolMinor & 0x0000ffff;
2333 rawBottom = in.toolMajor & 0x0000ffff;
2334 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2335 break;
2336 default:
2337 rawLeft = rawTop = rawRight = rawBottom = 0;
2338 break;
2339 }
2340
2341 // Adjust X,Y coords for device calibration
2342 // TODO: Adjust coverage coords?
2343 float xTransformed = in.x, yTransformed = in.y;
2344 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002345 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002346
Prabir Pradhan1728b212021-10-19 16:00:03 -07002347 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002348 float left, top, right, bottom;
2349
Prabir Pradhan1728b212021-10-19 16:00:03 -07002350 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002352 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2353 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2354 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2355 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002357 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002359 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002360 }
2361 break;
2362 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002363 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2364 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002365 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2366 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002368 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002370 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 }
2372 break;
2373 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2375 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002376 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2377 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002379 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002381 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 }
2383 break;
2384 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002385 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2386 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2387 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2388 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 break;
2390 }
2391
2392 // Write output coords.
2393 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2394 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002395 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2396 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2398 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2400 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2402 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2403 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002404 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2406 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2407 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2408 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2409 } else {
2410 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2411 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2412 }
2413
Chris Ye364fdb52020-08-05 15:07:56 -07002414 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002415 uint32_t id = in.id;
2416 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2417 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2418 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2419 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2420 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2421 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2422 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2423 }
2424
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 // Write output properties.
2426 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 properties.clear();
2428 properties.id = id;
2429 properties.toolType = in.toolType;
2430
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002431 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002433 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 }
2435}
2436
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002437std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2438 uint32_t policyFlags,
2439 PointerUsage pointerUsage) {
2440 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002441 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002442 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 mPointerUsage = pointerUsage;
2444 }
2445
2446 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002447 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002448 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002449 break;
Michael Wright227c5542020-07-02 18:30:52 +01002450 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002451 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452 break;
Michael Wright227c5542020-07-02 18:30:52 +01002453 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002454 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002455 break;
Michael Wright227c5542020-07-02 18:30:52 +01002456 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002457 break;
2458 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002459 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460}
2461
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002462std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2463 uint32_t policyFlags) {
2464 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002466 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002467 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 break;
Michael Wright227c5542020-07-02 18:30:52 +01002469 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002470 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002471 break;
Michael Wright227c5542020-07-02 18:30:52 +01002472 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 break;
Michael Wright227c5542020-07-02 18:30:52 +01002475 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476 break;
2477 }
2478
Michael Wright227c5542020-07-02 18:30:52 +01002479 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002480 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002481}
2482
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002483std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2484 uint32_t policyFlags,
2485 bool isTimeout) {
2486 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002487 // Update current gesture coordinates.
2488 bool cancelPreviousGesture, finishPreviousGesture;
2489 bool sendEvents =
2490 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2491 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002492 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002493 }
2494 if (finishPreviousGesture) {
2495 cancelPreviousGesture = false;
2496 }
2497
2498 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002499 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002500 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002501 if (finishPreviousGesture || cancelPreviousGesture) {
2502 mPointerController->clearSpots();
2503 }
2504
Michael Wright227c5542020-07-02 18:30:52 +01002505 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002506 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2507 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002508 mPointerGesture.currentGestureIdBits,
2509 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002510 }
2511 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002512 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002513 }
2514
2515 // Show or hide the pointer if needed.
2516 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002517 case PointerGesture::Mode::NEUTRAL:
2518 case PointerGesture::Mode::QUIET:
2519 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2520 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002521 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002522 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002523 }
2524 break;
Michael Wright227c5542020-07-02 18:30:52 +01002525 case PointerGesture::Mode::TAP:
2526 case PointerGesture::Mode::TAP_DRAG:
2527 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2528 case PointerGesture::Mode::HOVER:
2529 case PointerGesture::Mode::PRESS:
2530 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002531 // Unfade the pointer when the current gesture manipulates the
2532 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002533 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 break;
Michael Wright227c5542020-07-02 18:30:52 +01002535 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002536 // Fade the pointer when the current gesture manipulates a different
2537 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002538 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002539 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002540 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002541 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002542 }
2543 break;
2544 }
2545
2546 // Send events!
2547 int32_t metaState = getContext()->getGlobalMetaState();
2548 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002549 const MotionClassification classification =
2550 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2551 ? MotionClassification::TWO_FINGER_SWIPE
2552 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002554 uint32_t flags = 0;
2555
2556 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2557 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2558 }
2559
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002560 // Update last coordinates of pointers that have moved so that we observe the new
2561 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002562 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2563 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2564 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2565 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2566 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2567 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002568 bool moveNeeded = false;
2569 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2570 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2571 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2572 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2573 mPointerGesture.lastGestureIdBits.value);
2574 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2575 mPointerGesture.currentGestureCoords,
2576 mPointerGesture.currentGestureIdToIndex,
2577 mPointerGesture.lastGestureProperties,
2578 mPointerGesture.lastGestureCoords,
2579 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2580 if (buttonState != mLastCookedState.buttonState) {
2581 moveNeeded = true;
2582 }
2583 }
2584
2585 // Send motion events for all pointers that went up or were canceled.
2586 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2587 if (!dispatchedGestureIdBits.isEmpty()) {
2588 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002589 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002590 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002591 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002592 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2593 mPointerGesture.lastGestureProperties,
2594 mPointerGesture.lastGestureCoords,
2595 mPointerGesture.lastGestureIdToIndex,
2596 dispatchedGestureIdBits, -1, 0, 0,
2597 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002598
2599 dispatchedGestureIdBits.clear();
2600 } else {
2601 BitSet32 upGestureIdBits;
2602 if (finishPreviousGesture) {
2603 upGestureIdBits = dispatchedGestureIdBits;
2604 } else {
2605 upGestureIdBits.value =
2606 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2607 }
2608 while (!upGestureIdBits.isEmpty()) {
2609 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2610
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002611 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2612 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2613 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2614 mPointerGesture.lastGestureProperties,
2615 mPointerGesture.lastGestureCoords,
2616 mPointerGesture.lastGestureIdToIndex,
2617 dispatchedGestureIdBits, id, 0, 0,
2618 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002619
2620 dispatchedGestureIdBits.clearBit(id);
2621 }
2622 }
2623 }
2624
2625 // Send motion events for all pointers that moved.
2626 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002627 out.push_back(
2628 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2629 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2630 mPointerGesture.currentGestureProperties,
2631 mPointerGesture.currentGestureCoords,
2632 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2633 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002634 }
2635
2636 // Send motion events for all pointers that went down.
2637 if (down) {
2638 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2639 ~dispatchedGestureIdBits.value);
2640 while (!downGestureIdBits.isEmpty()) {
2641 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2642 dispatchedGestureIdBits.markBit(id);
2643
2644 if (dispatchedGestureIdBits.count() == 1) {
2645 mPointerGesture.downTime = when;
2646 }
2647
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002648 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2649 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2650 buttonState, 0, mPointerGesture.currentGestureProperties,
2651 mPointerGesture.currentGestureCoords,
2652 mPointerGesture.currentGestureIdToIndex,
2653 dispatchedGestureIdBits, id, 0, 0,
2654 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002655 }
2656 }
2657
2658 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002659 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002660 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2661 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2662 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2663 mPointerGesture.currentGestureProperties,
2664 mPointerGesture.currentGestureCoords,
2665 mPointerGesture.currentGestureIdToIndex,
2666 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2667 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002668 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2669 // Synthesize a hover move event after all pointers go up to indicate that
2670 // the pointer is hovering again even if the user is not currently touching
2671 // the touch pad. This ensures that a view will receive a fresh hover enter
2672 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002673 float x, y;
2674 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002675
2676 PointerProperties pointerProperties;
2677 pointerProperties.clear();
2678 pointerProperties.id = 0;
2679 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2680
2681 PointerCoords pointerCoords;
2682 pointerCoords.clear();
2683 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2684 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2685
2686 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002687 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2688 mSource, displayId, policyFlags,
2689 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2690 buttonState, MotionClassification::NONE,
2691 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2692 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2693 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002694 }
2695
2696 // Update state.
2697 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2698 if (!down) {
2699 mPointerGesture.lastGestureIdBits.clear();
2700 } else {
2701 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2702 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2703 uint32_t id = idBits.clearFirstMarkedBit();
2704 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2705 mPointerGesture.lastGestureProperties[index].copyFrom(
2706 mPointerGesture.currentGestureProperties[index]);
2707 mPointerGesture.lastGestureCoords[index].copyFrom(
2708 mPointerGesture.currentGestureCoords[index]);
2709 mPointerGesture.lastGestureIdToIndex[id] = index;
2710 }
2711 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002712 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002713}
2714
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002715std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2716 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002717 const MotionClassification classification =
2718 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2719 ? MotionClassification::TWO_FINGER_SWIPE
2720 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002721 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002722 // Cancel previously dispatches pointers.
2723 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2724 int32_t metaState = getContext()->getGlobalMetaState();
2725 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002726 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002727 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2728 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002729 mPointerGesture.lastGestureProperties,
2730 mPointerGesture.lastGestureCoords,
2731 mPointerGesture.lastGestureIdToIndex,
2732 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2733 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002734 }
2735
2736 // Reset the current pointer gesture.
2737 mPointerGesture.reset();
2738 mPointerVelocityControl.reset();
2739
2740 // Remove any current spots.
2741 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002742 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002743 mPointerController->clearSpots();
2744 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002745 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002746}
2747
2748bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2749 bool* outFinishPreviousGesture, bool isTimeout) {
2750 *outCancelPreviousGesture = false;
2751 *outFinishPreviousGesture = false;
2752
2753 // Handle TAP timeout.
2754 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002755 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002756
Michael Wright227c5542020-07-02 18:30:52 +01002757 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002758 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2759 // The tap/drag timeout has not yet expired.
2760 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2761 mConfig.pointerGestureTapDragInterval);
2762 } else {
2763 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002764 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002765 *outFinishPreviousGesture = true;
2766
2767 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002768 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002769 mPointerGesture.currentGestureIdBits.clear();
2770
2771 mPointerVelocityControl.reset();
2772 return true;
2773 }
2774 }
2775
2776 // We did not handle this timeout.
2777 return false;
2778 }
2779
2780 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2781 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2782
2783 // Update the velocity tracker.
2784 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002785 std::vector<float> positionsX;
2786 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002787 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 uint32_t id = idBits.clearFirstMarkedBit();
2789 const RawPointerData::Pointer& pointer =
2790 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002791 positionsX.push_back(pointer.x * mPointerXMovementScale);
2792 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002793 }
2794 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002795 {{AMOTION_EVENT_AXIS_X, positionsX},
2796 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 }
2798
2799 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2800 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002801 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2802 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2803 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002804 mPointerGesture.resetTap();
2805 }
2806
2807 // Pick a new active touch id if needed.
2808 // Choose an arbitrary pointer that just went down, if there is one.
2809 // Otherwise choose an arbitrary remaining pointer.
2810 // This guarantees we always have an active touch id when there is at least one pointer.
2811 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002812 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002813 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002814 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815 mPointerGesture.firstTouchTime = when;
2816 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002817 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2818 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2819 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2820 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002821 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002822 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823
2824 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002825 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002827 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2828 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2829 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002830 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002831 *outFinishPreviousGesture = true;
2832 }
2833
2834 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002835 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002836 mPointerGesture.currentGestureIdBits.clear();
2837
2838 mPointerVelocityControl.reset();
2839 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2840 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2841 // The pointer follows the active touch point.
2842 // Emit DOWN, MOVE, UP events at the pointer location.
2843 //
2844 // Only the active touch matters; other fingers are ignored. This policy helps
2845 // to handle the case where the user places a second finger on the touch pad
2846 // to apply the necessary force to depress an integrated button below the surface.
2847 // We don't want the second finger to be delivered to applications.
2848 //
2849 // For this to work well, we need to make sure to track the pointer that is really
2850 // active. If the user first puts one finger down to click then adds another
2851 // finger to drag then the active pointer should switch to the finger that is
2852 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002853 ALOGD_IF(DEBUG_GESTURES,
2854 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2855 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002857 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002858 *outFinishPreviousGesture = true;
2859 mPointerGesture.activeGestureId = 0;
2860 }
2861
2862 // Switch pointers if needed.
2863 // Find the fastest pointer and follow it.
2864 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002865 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002866 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002867 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002868 ALOGD_IF(DEBUG_GESTURES,
2869 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2870 "bestSpeed=%0.3f",
2871 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 }
2873 }
2874
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002876 // When using spots, the click will occur at the position of the anchor
2877 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002878 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002879 } else {
2880 mPointerVelocityControl.reset();
2881 }
2882
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002883 float x, y;
2884 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885
Michael Wright227c5542020-07-02 18:30:52 +01002886 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002887 mPointerGesture.currentGestureIdBits.clear();
2888 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2889 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2890 mPointerGesture.currentGestureProperties[0].clear();
2891 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2892 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2893 mPointerGesture.currentGestureCoords[0].clear();
2894 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2895 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2896 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2897 } else if (currentFingerCount == 0) {
2898 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002899 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002900 *outFinishPreviousGesture = true;
2901 }
2902
2903 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2904 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2905 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002906 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2907 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002908 lastFingerCount == 1) {
2909 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002910 float x, y;
2911 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002912 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2913 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002914 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002915
2916 mPointerGesture.tapUpTime = when;
2917 getContext()->requestTimeoutAtTime(when +
2918 mConfig.pointerGestureTapDragInterval);
2919
2920 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002921 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 mPointerGesture.currentGestureIdBits.clear();
2923 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2924 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2925 mPointerGesture.currentGestureProperties[0].clear();
2926 mPointerGesture.currentGestureProperties[0].id =
2927 mPointerGesture.activeGestureId;
2928 mPointerGesture.currentGestureProperties[0].toolType =
2929 AMOTION_EVENT_TOOL_TYPE_FINGER;
2930 mPointerGesture.currentGestureCoords[0].clear();
2931 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2932 mPointerGesture.tapX);
2933 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2934 mPointerGesture.tapY);
2935 mPointerGesture.currentGestureCoords[0]
2936 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2937
2938 tapped = true;
2939 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002940 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2941 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002942 }
2943 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002944 if (DEBUG_GESTURES) {
2945 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2946 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2947 (when - mPointerGesture.tapDownTime) * 0.000001f);
2948 } else {
2949 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2950 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 }
2953 }
2954
2955 mPointerVelocityControl.reset();
2956
2957 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002958 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002959 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002960 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002961 mPointerGesture.currentGestureIdBits.clear();
2962 }
2963 } else if (currentFingerCount == 1) {
2964 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2965 // The pointer follows the active touch point.
2966 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2967 // When in TAP_DRAG, emit MOVE events at the pointer location.
2968 ALOG_ASSERT(activeTouchId >= 0);
2969
Michael Wright227c5542020-07-02 18:30:52 +01002970 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2971 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002972 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002973 float x, y;
2974 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002975 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2976 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002977 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002979 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2980 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 }
2982 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002983 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2984 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002985 }
Michael Wright227c5542020-07-02 18:30:52 +01002986 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2987 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 }
2989
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002992 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002993 } else {
2994 mPointerVelocityControl.reset();
2995 }
2996
2997 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002998 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002999 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003000 down = true;
3001 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003002 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003003 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003004 *outFinishPreviousGesture = true;
3005 }
3006 mPointerGesture.activeGestureId = 0;
3007 down = false;
3008 }
3009
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003010 float x, y;
3011 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003012
3013 mPointerGesture.currentGestureIdBits.clear();
3014 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3015 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3016 mPointerGesture.currentGestureProperties[0].clear();
3017 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3018 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3019 mPointerGesture.currentGestureCoords[0].clear();
3020 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3021 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3022 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3023 down ? 1.0f : 0.0f);
3024
3025 if (lastFingerCount == 0 && currentFingerCount != 0) {
3026 mPointerGesture.resetTap();
3027 mPointerGesture.tapDownTime = when;
3028 mPointerGesture.tapX = x;
3029 mPointerGesture.tapY = y;
3030 }
3031 } else {
3032 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003033 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003034 }
3035
3036 mPointerController->setButtonState(mCurrentRawState.buttonState);
3037
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003038 if (DEBUG_GESTURES) {
3039 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3040 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3041 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3042 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3043 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3044 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3045 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3046 uint32_t id = idBits.clearFirstMarkedBit();
3047 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3048 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3049 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3050 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3051 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3052 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3053 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3054 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3055 }
3056 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3057 uint32_t id = idBits.clearFirstMarkedBit();
3058 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3059 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3060 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3061 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3062 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3063 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3064 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3065 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3066 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003067 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003068 return true;
3069}
3070
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003071bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3072 if (mPointerGesture.activeTouchId < 0) {
3073 mPointerGesture.resetQuietTime();
3074 return false;
3075 }
3076
3077 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3078 return true;
3079 }
3080
3081 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3082 bool isQuietTime = false;
3083 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3084 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3085 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3086 currentFingerCount < 2) {
3087 // Enter quiet time when exiting swipe or freeform state.
3088 // This is to prevent accidentally entering the hover state and flinging the
3089 // pointer when finishing a swipe and there is still one pointer left onscreen.
3090 isQuietTime = true;
3091 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3092 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3093 // Enter quiet time when releasing the button and there are still two or more
3094 // fingers down. This may indicate that one finger was used to press the button
3095 // but it has not gone up yet.
3096 isQuietTime = true;
3097 }
3098 if (isQuietTime) {
3099 mPointerGesture.quietTime = when;
3100 }
3101 return isQuietTime;
3102}
3103
3104std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3105 int32_t bestId = -1;
3106 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3107 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3108 uint32_t id = idBits.clearFirstMarkedBit();
3109 std::optional<float> vx =
3110 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3111 std::optional<float> vy =
3112 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3113 if (vx && vy) {
3114 float speed = hypotf(*vx, *vy);
3115 if (speed > bestSpeed) {
3116 bestId = id;
3117 bestSpeed = speed;
3118 }
3119 }
3120 }
3121 return std::make_pair(bestId, bestSpeed);
3122}
3123
3124void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3125 bool* finishPreviousGesture) {
3126 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3127 // to move before deciding what to do.
3128 //
3129 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3130 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3131 // just a press or long-press at the pointer location.
3132 //
3133 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3134 // pointer location.
3135 //
3136 // When the two fingers move enough or when additional fingers are added, we make a decision to
3137 // transition into SWIPE or FREEFORM mode accordingly.
3138 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3139 ALOG_ASSERT(activeTouchId >= 0);
3140
3141 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3142 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3143 bool settled =
3144 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3145 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3146 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3147 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3148 *finishPreviousGesture = true;
3149 } else if (!settled && currentFingerCount > lastFingerCount) {
3150 // Additional pointers have gone down but not yet settled.
3151 // Reset the gesture.
3152 ALOGD_IF(DEBUG_GESTURES,
3153 "Gestures: Resetting gesture since additional pointers went down for "
3154 "MULTITOUCH, settle time remaining %0.3fms",
3155 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3156 when) * 0.000001f);
3157 *cancelPreviousGesture = true;
3158 } else {
3159 // Continue previous gesture.
3160 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3161 }
3162
3163 if (*finishPreviousGesture || *cancelPreviousGesture) {
3164 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3165 mPointerGesture.activeGestureId = 0;
3166 mPointerGesture.referenceIdBits.clear();
3167 mPointerVelocityControl.reset();
3168
3169 // Use the centroid and pointer location as the reference points for the gesture.
3170 ALOGD_IF(DEBUG_GESTURES,
3171 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3172 "%0.3fms",
3173 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3174 when) * 0.000001f);
3175 mCurrentRawState.rawPointerData
3176 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3177 &mPointerGesture.referenceTouchY);
3178 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3179 &mPointerGesture.referenceGestureY);
3180 }
3181
3182 // Clear the reference deltas for fingers not yet included in the reference calculation.
3183 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3184 ~mPointerGesture.referenceIdBits.value);
3185 !idBits.isEmpty();) {
3186 uint32_t id = idBits.clearFirstMarkedBit();
3187 mPointerGesture.referenceDeltas[id].dx = 0;
3188 mPointerGesture.referenceDeltas[id].dy = 0;
3189 }
3190 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3191
3192 // Add delta for all fingers and calculate a common movement delta.
3193 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3194 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3195 mCurrentCookedState.fingerIdBits.value);
3196 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3197 bool first = (idBits == commonIdBits);
3198 uint32_t id = idBits.clearFirstMarkedBit();
3199 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3200 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3201 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3202 delta.dx += cpd.x - lpd.x;
3203 delta.dy += cpd.y - lpd.y;
3204
3205 if (first) {
3206 commonDeltaRawX = delta.dx;
3207 commonDeltaRawY = delta.dy;
3208 } else {
3209 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3210 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3211 }
3212 }
3213
3214 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3215 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3216 float dist[MAX_POINTER_ID + 1];
3217 int32_t distOverThreshold = 0;
3218 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3219 uint32_t id = idBits.clearFirstMarkedBit();
3220 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3221 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3222 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3223 distOverThreshold += 1;
3224 }
3225 }
3226
3227 // Only transition when at least two pointers have moved further than
3228 // the minimum distance threshold.
3229 if (distOverThreshold >= 2) {
3230 if (currentFingerCount > 2) {
3231 // There are more than two pointers, switch to FREEFORM.
3232 ALOGD_IF(DEBUG_GESTURES,
3233 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3234 currentFingerCount);
3235 *cancelPreviousGesture = true;
3236 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3237 } else {
3238 // There are exactly two pointers.
3239 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3240 uint32_t id1 = idBits.clearFirstMarkedBit();
3241 uint32_t id2 = idBits.firstMarkedBit();
3242 const RawPointerData::Pointer& p1 =
3243 mCurrentRawState.rawPointerData.pointerForId(id1);
3244 const RawPointerData::Pointer& p2 =
3245 mCurrentRawState.rawPointerData.pointerForId(id2);
3246 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3247 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3248 // There are two pointers but they are too far apart for a SWIPE,
3249 // switch to FREEFORM.
3250 ALOGD_IF(DEBUG_GESTURES,
3251 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3252 mutualDistance, mPointerGestureMaxSwipeWidth);
3253 *cancelPreviousGesture = true;
3254 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3255 } else {
3256 // There are two pointers. Wait for both pointers to start moving
3257 // before deciding whether this is a SWIPE or FREEFORM gesture.
3258 float dist1 = dist[id1];
3259 float dist2 = dist[id2];
3260 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3261 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3262 // Calculate the dot product of the displacement vectors.
3263 // When the vectors are oriented in approximately the same direction,
3264 // the angle betweeen them is near zero and the cosine of the angle
3265 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3266 // mag(v2).
3267 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3268 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3269 float dx1 = delta1.dx * mPointerXZoomScale;
3270 float dy1 = delta1.dy * mPointerYZoomScale;
3271 float dx2 = delta2.dx * mPointerXZoomScale;
3272 float dy2 = delta2.dy * mPointerYZoomScale;
3273 float dot = dx1 * dx2 + dy1 * dy2;
3274 float cosine = dot / (dist1 * dist2); // denominator always > 0
3275 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3276 // Pointers are moving in the same direction. Switch to SWIPE.
3277 ALOGD_IF(DEBUG_GESTURES,
3278 "Gestures: PRESS transitioned to SWIPE, "
3279 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3280 "cosine %0.3f >= %0.3f",
3281 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3282 mConfig.pointerGestureMultitouchMinDistance, cosine,
3283 mConfig.pointerGestureSwipeTransitionAngleCosine);
3284 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3285 } else {
3286 // Pointers are moving in different directions. Switch to FREEFORM.
3287 ALOGD_IF(DEBUG_GESTURES,
3288 "Gestures: PRESS transitioned to FREEFORM, "
3289 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3290 "cosine %0.3f < %0.3f",
3291 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3292 mConfig.pointerGestureMultitouchMinDistance, cosine,
3293 mConfig.pointerGestureSwipeTransitionAngleCosine);
3294 *cancelPreviousGesture = true;
3295 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3296 }
3297 }
3298 }
3299 }
3300 }
3301 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3302 // Switch from SWIPE to FREEFORM if additional pointers go down.
3303 // Cancel previous gesture.
3304 if (currentFingerCount > 2) {
3305 ALOGD_IF(DEBUG_GESTURES,
3306 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3307 currentFingerCount);
3308 *cancelPreviousGesture = true;
3309 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3310 }
3311 }
3312
3313 // Move the reference points based on the overall group motion of the fingers
3314 // except in PRESS mode while waiting for a transition to occur.
3315 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3316 (commonDeltaRawX || commonDeltaRawY)) {
3317 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3318 uint32_t id = idBits.clearFirstMarkedBit();
3319 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3320 delta.dx = 0;
3321 delta.dy = 0;
3322 }
3323
3324 mPointerGesture.referenceTouchX += commonDeltaRawX;
3325 mPointerGesture.referenceTouchY += commonDeltaRawY;
3326
3327 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3328 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3329
3330 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3331 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3332
3333 mPointerGesture.referenceGestureX += commonDeltaX;
3334 mPointerGesture.referenceGestureY += commonDeltaY;
3335 }
3336
3337 // Report gestures.
3338 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3339 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3340 // PRESS or SWIPE mode.
3341 ALOGD_IF(DEBUG_GESTURES,
3342 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3343 "currentTouchPointerCount=%d",
3344 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3345 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3346
3347 mPointerGesture.currentGestureIdBits.clear();
3348 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3349 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3350 mPointerGesture.currentGestureProperties[0].clear();
3351 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3352 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3353 mPointerGesture.currentGestureCoords[0].clear();
3354 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3355 mPointerGesture.referenceGestureX);
3356 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3357 mPointerGesture.referenceGestureY);
3358 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3359 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3360 float xOffset = static_cast<float>(commonDeltaRawX) /
3361 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3362 float yOffset = static_cast<float>(commonDeltaRawY) /
3363 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3364 mPointerGesture.currentGestureCoords[0]
3365 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3366 mPointerGesture.currentGestureCoords[0]
3367 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3368 }
3369 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3370 // FREEFORM mode.
3371 ALOGD_IF(DEBUG_GESTURES,
3372 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3373 "currentTouchPointerCount=%d",
3374 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3375 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3376
3377 mPointerGesture.currentGestureIdBits.clear();
3378
3379 BitSet32 mappedTouchIdBits;
3380 BitSet32 usedGestureIdBits;
3381 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3382 // Initially, assign the active gesture id to the active touch point
3383 // if there is one. No other touch id bits are mapped yet.
3384 if (!*cancelPreviousGesture) {
3385 mappedTouchIdBits.markBit(activeTouchId);
3386 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3387 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3388 mPointerGesture.activeGestureId;
3389 } else {
3390 mPointerGesture.activeGestureId = -1;
3391 }
3392 } else {
3393 // Otherwise, assume we mapped all touches from the previous frame.
3394 // Reuse all mappings that are still applicable.
3395 mappedTouchIdBits.value =
3396 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3397 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3398
3399 // Check whether we need to choose a new active gesture id because the
3400 // current went went up.
3401 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3402 ~mCurrentCookedState.fingerIdBits.value);
3403 !upTouchIdBits.isEmpty();) {
3404 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3405 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3406 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3407 mPointerGesture.activeGestureId = -1;
3408 break;
3409 }
3410 }
3411 }
3412
3413 ALOGD_IF(DEBUG_GESTURES,
3414 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3415 "activeGestureId=%d",
3416 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3417
3418 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3419 for (uint32_t i = 0; i < currentFingerCount; i++) {
3420 uint32_t touchId = idBits.clearFirstMarkedBit();
3421 uint32_t gestureId;
3422 if (!mappedTouchIdBits.hasBit(touchId)) {
3423 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3424 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3425 ALOGD_IF(DEBUG_GESTURES,
3426 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3427 gestureId);
3428 } else {
3429 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3430 ALOGD_IF(DEBUG_GESTURES,
3431 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3432 touchId, gestureId);
3433 }
3434 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3435 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3436
3437 const RawPointerData::Pointer& pointer =
3438 mCurrentRawState.rawPointerData.pointerForId(touchId);
3439 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3440 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3441 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3442
3443 mPointerGesture.currentGestureProperties[i].clear();
3444 mPointerGesture.currentGestureProperties[i].id = gestureId;
3445 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3446 mPointerGesture.currentGestureCoords[i].clear();
3447 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3448 mPointerGesture.referenceGestureX +
3449 deltaX);
3450 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3451 mPointerGesture.referenceGestureY +
3452 deltaY);
3453 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3454 }
3455
3456 if (mPointerGesture.activeGestureId < 0) {
3457 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3458 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3459 mPointerGesture.activeGestureId);
3460 }
3461 }
3462}
3463
Harry Cutts714d1ad2022-08-24 16:36:43 +00003464void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3465 const RawPointerData::Pointer& currentPointer =
3466 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3467 const RawPointerData::Pointer& lastPointer =
3468 mLastRawState.rawPointerData.pointerForId(pointerId);
3469 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3470 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3471
3472 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3473 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3474
3475 mPointerController->move(deltaX, deltaY);
3476}
3477
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003478std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3479 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003480 mPointerSimple.currentCoords.clear();
3481 mPointerSimple.currentProperties.clear();
3482
3483 bool down, hovering;
3484 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3485 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3486 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003487 mPointerController
3488 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3489 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003490
3491 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3492 down = !hovering;
3493
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003494 float x, y;
3495 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003496 mPointerSimple.currentCoords.copyFrom(
3497 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3498 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3499 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3500 mPointerSimple.currentProperties.id = 0;
3501 mPointerSimple.currentProperties.toolType =
3502 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3503 } else {
3504 down = false;
3505 hovering = false;
3506 }
3507
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003508 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509}
3510
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003511std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3512 uint32_t policyFlags) {
3513 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003514}
3515
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003516std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3517 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003518 mPointerSimple.currentCoords.clear();
3519 mPointerSimple.currentProperties.clear();
3520
3521 bool down, hovering;
3522 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3523 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003524 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003525 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003526 } else {
3527 mPointerVelocityControl.reset();
3528 }
3529
3530 down = isPointerDown(mCurrentRawState.buttonState);
3531 hovering = !down;
3532
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003533 float x, y;
3534 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003535 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003536 mPointerSimple.currentCoords.copyFrom(
3537 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3538 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3539 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3540 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3541 hovering ? 0.0f : 1.0f);
3542 mPointerSimple.currentProperties.id = 0;
3543 mPointerSimple.currentProperties.toolType =
3544 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3545 } else {
3546 mPointerVelocityControl.reset();
3547
3548 down = false;
3549 hovering = false;
3550 }
3551
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003552 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003553}
3554
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003555std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3556 uint32_t policyFlags) {
3557 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003558
3559 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003560
3561 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003562}
3563
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003564std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3565 uint32_t policyFlags, bool down,
3566 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003567 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3568 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003569 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571
3572 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003573 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003574 mPointerController->clearSpots();
3575 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003576 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003577 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003578 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003579 }
Garfield Tan9514d782020-11-10 16:37:23 -08003580 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003581
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003582 float xCursorPosition, yCursorPosition;
3583 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003584
3585 if (mPointerSimple.down && !down) {
3586 mPointerSimple.down = false;
3587
3588 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003589 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3590 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3591 0, metaState, mLastRawState.buttonState,
3592 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3593 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3594 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3595 yCursorPosition, mPointerSimple.downTime,
3596 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003597 }
3598
3599 if (mPointerSimple.hovering && !hovering) {
3600 mPointerSimple.hovering = false;
3601
3602 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003603 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3604 mSource, displayId, policyFlags,
3605 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3606 mLastRawState.buttonState, MotionClassification::NONE,
3607 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3608 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3609 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3610 yCursorPosition, mPointerSimple.downTime,
3611 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003612 }
3613
3614 if (down) {
3615 if (!mPointerSimple.down) {
3616 mPointerSimple.down = true;
3617 mPointerSimple.downTime = when;
3618
3619 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003620 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3621 mSource, displayId, policyFlags,
3622 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3623 mCurrentRawState.buttonState, MotionClassification::NONE,
3624 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 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003632 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3633 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3634 0, 0, metaState, mCurrentRawState.buttonState,
3635 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3636 &mPointerSimple.currentProperties,
3637 &mPointerSimple.currentCoords, mOrientedXPrecision,
3638 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3639 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003640 }
3641
3642 if (hovering) {
3643 if (!mPointerSimple.hovering) {
3644 mPointerSimple.hovering = true;
3645
3646 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003647 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3648 mSource, displayId, policyFlags,
3649 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3650 mCurrentRawState.buttonState, MotionClassification::NONE,
3651 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3652 &mPointerSimple.currentProperties,
3653 &mPointerSimple.currentCoords, mOrientedXPrecision,
3654 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3655 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003656 }
3657
3658 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003659 out.push_back(
3660 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3661 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3662 metaState, mCurrentRawState.buttonState,
3663 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3664 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3665 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3666 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003667 }
3668
3669 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3670 float vscroll = mCurrentRawState.rawVScroll;
3671 float hscroll = mCurrentRawState.rawHScroll;
3672 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3673 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3674
3675 // Send scroll.
3676 PointerCoords pointerCoords;
3677 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3678 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3679 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3680
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003681 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3682 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3683 0, 0, metaState, mCurrentRawState.buttonState,
3684 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3685 &mPointerSimple.currentProperties, &pointerCoords,
3686 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3687 yCursorPosition, mPointerSimple.downTime,
3688 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003689 }
3690
3691 // Save state.
3692 if (down || hovering) {
3693 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3694 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003695 mPointerSimple.displayId = displayId;
3696 mPointerSimple.source = mSource;
3697 mPointerSimple.lastCursorX = xCursorPosition;
3698 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003699 } else {
3700 mPointerSimple.reset();
3701 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003702 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003703}
3704
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003705std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3706 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003707 std::list<NotifyArgs> out;
3708 if (mPointerSimple.down || mPointerSimple.hovering) {
3709 int32_t metaState = getContext()->getGlobalMetaState();
3710 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3711 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3712 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3713 metaState, mLastRawState.buttonState,
3714 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3715 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3716 mOrientedXPrecision, mOrientedYPrecision,
3717 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3718 mPointerSimple.downTime,
3719 /* videoFrames */ {}));
3720 if (mPointerController != nullptr) {
3721 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3722 }
3723 }
3724 mPointerSimple.reset();
3725 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003726}
3727
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003728NotifyMotionArgs TouchInputMapper::dispatchMotion(
3729 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3730 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003731 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3732 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003733 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003734 PointerCoords pointerCoords[MAX_POINTERS];
3735 PointerProperties pointerProperties[MAX_POINTERS];
3736 uint32_t pointerCount = 0;
3737 while (!idBits.isEmpty()) {
3738 uint32_t id = idBits.clearFirstMarkedBit();
3739 uint32_t index = idToIndex[id];
3740 pointerProperties[pointerCount].copyFrom(properties[index]);
3741 pointerCoords[pointerCount].copyFrom(coords[index]);
3742
3743 if (changedId >= 0 && id == uint32_t(changedId)) {
3744 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3745 }
3746
3747 pointerCount += 1;
3748 }
3749
3750 ALOG_ASSERT(pointerCount != 0);
3751
3752 if (changedId >= 0 && pointerCount == 1) {
3753 // Replace initial down and final up action.
3754 // We can compare the action without masking off the changed pointer index
3755 // because we know the index is 0.
3756 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3757 action = AMOTION_EVENT_ACTION_DOWN;
3758 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003759 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3760 action = AMOTION_EVENT_ACTION_CANCEL;
3761 } else {
3762 action = AMOTION_EVENT_ACTION_UP;
3763 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003764 } else {
3765 // Can't happen.
3766 ALOG_ASSERT(false);
3767 }
3768 }
3769 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3770 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003771 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003772 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003773 }
3774 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3775 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003776 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003777 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003778 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003779 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3780 policyFlags, action, actionButton, flags, metaState, buttonState,
3781 classification, edgeFlags, pointerCount, pointerProperties,
3782 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3783 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003784}
3785
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003786std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3787 std::list<NotifyArgs> out;
3788 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3789 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3790 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003791}
3792
Prabir Pradhan1728b212021-10-19 16:00:03 -07003793// Transform input device coordinates to display panel coordinates.
3794void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003795 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3796 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3797
arthurhunga36b28e2020-12-29 20:28:15 +08003798 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3799 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3800
Prabir Pradhan1728b212021-10-19 16:00:03 -07003801 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003802 // 0 - no swap and reverse.
3803 // 90 - swap x/y and reverse y.
3804 // 180 - reverse x, y.
3805 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003806 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003807 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003808 x = xScaled;
3809 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003810 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003811 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003812 y = xScaledMax;
3813 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003814 break;
3815 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003816 x = xScaledMax;
3817 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003818 break;
3819 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003820 y = xScaled;
3821 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003822 break;
3823 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003824 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003825 }
3826}
3827
Prabir Pradhan1728b212021-10-19 16:00:03 -07003828bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003829 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3830 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3831
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003832 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003833 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003834 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003835 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003836}
3837
3838const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3839 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003840 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3841 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3842 "left=%d, top=%d, right=%d, bottom=%d",
3843 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3844 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003845
3846 if (virtualKey.isHit(x, y)) {
3847 return &virtualKey;
3848 }
3849 }
3850
3851 return nullptr;
3852}
3853
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003854void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3855 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3856 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003857
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003858 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003859
3860 if (currentPointerCount == 0) {
3861 // No pointers to assign.
3862 return;
3863 }
3864
3865 if (lastPointerCount == 0) {
3866 // All pointers are new.
3867 for (uint32_t i = 0; i < currentPointerCount; i++) {
3868 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003869 current.rawPointerData.pointers[i].id = id;
3870 current.rawPointerData.idToIndex[id] = i;
3871 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003872 }
3873 return;
3874 }
3875
3876 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003877 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003878 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003879 uint32_t id = last.rawPointerData.pointers[0].id;
3880 current.rawPointerData.pointers[0].id = id;
3881 current.rawPointerData.idToIndex[id] = 0;
3882 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003883 return;
3884 }
3885
3886 // General case.
3887 // We build a heap of squared euclidean distances between current and last pointers
3888 // associated with the current and last pointer indices. Then, we find the best
3889 // match (by distance) for each current pointer.
3890 // The pointers must have the same tool type but it is possible for them to
3891 // transition from hovering to touching or vice-versa while retaining the same id.
3892 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3893
3894 uint32_t heapSize = 0;
3895 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3896 currentPointerIndex++) {
3897 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3898 lastPointerIndex++) {
3899 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003900 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003901 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003902 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003903 if (currentPointer.toolType == lastPointer.toolType) {
3904 int64_t deltaX = currentPointer.x - lastPointer.x;
3905 int64_t deltaY = currentPointer.y - lastPointer.y;
3906
3907 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3908
3909 // Insert new element into the heap (sift up).
3910 heap[heapSize].currentPointerIndex = currentPointerIndex;
3911 heap[heapSize].lastPointerIndex = lastPointerIndex;
3912 heap[heapSize].distance = distance;
3913 heapSize += 1;
3914 }
3915 }
3916 }
3917
3918 // Heapify
3919 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3920 startIndex -= 1;
3921 for (uint32_t parentIndex = startIndex;;) {
3922 uint32_t childIndex = parentIndex * 2 + 1;
3923 if (childIndex >= heapSize) {
3924 break;
3925 }
3926
3927 if (childIndex + 1 < heapSize &&
3928 heap[childIndex + 1].distance < heap[childIndex].distance) {
3929 childIndex += 1;
3930 }
3931
3932 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3933 break;
3934 }
3935
3936 swap(heap[parentIndex], heap[childIndex]);
3937 parentIndex = childIndex;
3938 }
3939 }
3940
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003941 if (DEBUG_POINTER_ASSIGNMENT) {
3942 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3943 for (size_t i = 0; i < heapSize; i++) {
3944 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3945 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3946 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003947 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003948
3949 // Pull matches out by increasing order of distance.
3950 // To avoid reassigning pointers that have already been matched, the loop keeps track
3951 // of which last and current pointers have been matched using the matchedXXXBits variables.
3952 // It also tracks the used pointer id bits.
3953 BitSet32 matchedLastBits(0);
3954 BitSet32 matchedCurrentBits(0);
3955 BitSet32 usedIdBits(0);
3956 bool first = true;
3957 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3958 while (heapSize > 0) {
3959 if (first) {
3960 // The first time through the loop, we just consume the root element of
3961 // the heap (the one with smallest distance).
3962 first = false;
3963 } else {
3964 // Previous iterations consumed the root element of the heap.
3965 // Pop root element off of the heap (sift down).
3966 heap[0] = heap[heapSize];
3967 for (uint32_t parentIndex = 0;;) {
3968 uint32_t childIndex = parentIndex * 2 + 1;
3969 if (childIndex >= heapSize) {
3970 break;
3971 }
3972
3973 if (childIndex + 1 < heapSize &&
3974 heap[childIndex + 1].distance < heap[childIndex].distance) {
3975 childIndex += 1;
3976 }
3977
3978 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3979 break;
3980 }
3981
3982 swap(heap[parentIndex], heap[childIndex]);
3983 parentIndex = childIndex;
3984 }
3985
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003986 if (DEBUG_POINTER_ASSIGNMENT) {
3987 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3988 for (size_t j = 0; j < heapSize; j++) {
3989 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3990 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3991 heap[j].distance);
3992 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003993 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003994 }
3995
3996 heapSize -= 1;
3997
3998 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3999 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4000
4001 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4002 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4003
4004 matchedCurrentBits.markBit(currentPointerIndex);
4005 matchedLastBits.markBit(lastPointerIndex);
4006
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004007 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4008 current.rawPointerData.pointers[currentPointerIndex].id = id;
4009 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4010 current.rawPointerData.markIdBit(id,
4011 current.rawPointerData.isHovering(
4012 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004013 usedIdBits.markBit(id);
4014
Harry Cutts45483602022-08-24 14:36:48 +00004015 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4016 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4017 ", distance=%" PRIu64,
4018 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004019 break;
4020 }
4021 }
4022
4023 // Assign fresh ids to pointers that were not matched in the process.
4024 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4025 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4026 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4027
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004028 current.rawPointerData.pointers[currentPointerIndex].id = id;
4029 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4030 current.rawPointerData.markIdBit(id,
4031 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004032
Harry Cutts45483602022-08-24 14:36:48 +00004033 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4034 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4035 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004036 }
4037}
4038
4039int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4040 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4041 return AKEY_STATE_VIRTUAL;
4042 }
4043
4044 for (const VirtualKey& virtualKey : mVirtualKeys) {
4045 if (virtualKey.keyCode == keyCode) {
4046 return AKEY_STATE_UP;
4047 }
4048 }
4049
4050 return AKEY_STATE_UNKNOWN;
4051}
4052
4053int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4054 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4055 return AKEY_STATE_VIRTUAL;
4056 }
4057
4058 for (const VirtualKey& virtualKey : mVirtualKeys) {
4059 if (virtualKey.scanCode == scanCode) {
4060 return AKEY_STATE_UP;
4061 }
4062 }
4063
4064 return AKEY_STATE_UNKNOWN;
4065}
4066
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004067bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4068 const std::vector<int32_t>& keyCodes,
4069 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004070 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004071 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004072 if (virtualKey.keyCode == keyCodes[i]) {
4073 outFlags[i] = 1;
4074 }
4075 }
4076 }
4077
4078 return true;
4079}
4080
4081std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4082 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004083 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004084 return std::make_optional(mPointerController->getDisplayId());
4085 } else {
4086 return std::make_optional(mViewport.displayId);
4087 }
4088 }
4089 return std::nullopt;
4090}
4091
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004092} // namespace android