blob: 605b8f8377e01dcd7d3fee4715f9ea65bf1236f4 [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);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700440}
441
442void TouchInputMapper::dumpParameters(std::string& dump) {
443 dump += INDENT3 "Parameters:\n";
444
Dominik Laskowski75788452021-02-09 18:51:25 -0800445 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446
Dominik Laskowski75788452021-02-09 18:51:25 -0800447 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448
449 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
450 "displayId='%s'\n",
451 toString(mParameters.hasAssociatedDisplay),
452 toString(mParameters.associatedDisplayIsExternal),
453 mParameters.uniqueDisplayId.c_str());
454 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800455 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000456 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457}
458
459void TouchInputMapper::configureRawPointerAxes() {
460 mRawPointerAxes.clear();
461}
462
463void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
464 dump += INDENT3 "Raw Touch Axes:\n";
465 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
466 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
467 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
468 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
469 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
470 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
471 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
472 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
473 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
474 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
475 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
476 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
477 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
478}
479
480bool TouchInputMapper::hasExternalStylus() const {
481 return mExternalStylusConnected;
482}
483
484/**
485 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000486 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800487 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000488 * 3. Get the matching viewport by either unique id in idc file or by the display type
489 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800490 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700491 */
492std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800493 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000494 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800495 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496 }
497
Christine Franks2a2293c2022-01-18 11:51:16 -0800498 const std::optional<std::string> associatedDisplayUniqueId =
499 getDeviceContext().getAssociatedDisplayUniqueId();
500 if (associatedDisplayUniqueId) {
501 return getDeviceContext().getAssociatedViewport();
502 }
503
Michael Wright227c5542020-07-02 18:30:52 +0100504 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800505 std::optional<DisplayViewport> viewport =
506 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
507 if (viewport) {
508 return viewport;
509 } else {
510 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
511 mConfig.defaultPointerDisplayId);
512 }
513 }
514
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700515 // Check if uniqueDisplayId is specified in idc file.
516 if (!mParameters.uniqueDisplayId.empty()) {
517 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
518 }
519
520 ViewportType viewportTypeToUse;
521 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100522 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700523 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100524 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700525 }
526
527 std::optional<DisplayViewport> viewport =
528 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100529 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700530 ALOGW("Input device %s should be associated with external display, "
531 "fallback to internal one for the external viewport is not found.",
532 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100533 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700534 }
535
536 return viewport;
537 }
538
539 // No associated display, return a non-display viewport.
540 DisplayViewport newViewport;
541 // Raw width and height in the natural orientation.
542 int32_t rawWidth = mRawPointerAxes.getRawWidth();
543 int32_t rawHeight = mRawPointerAxes.getRawHeight();
544 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
545 return std::make_optional(newViewport);
546}
547
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800548int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
549 if (resolution < 0) {
550 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
551 getDeviceName().c_str());
552 return 0;
553 }
554 return resolution;
555}
556
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800557void TouchInputMapper::initializeSizeRanges() {
558 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
559 mSizeScale = 0.0f;
560 return;
561 }
562
563 // Size of diagonal axis.
564 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
565
566 // Size factors.
567 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
568 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
569 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
570 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
571 } else {
572 mSizeScale = 0.0f;
573 }
574
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700575 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
576 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
577 .source = mSource,
578 .min = 0,
579 .max = diagonalSize,
580 .flat = 0,
581 .fuzz = 0,
582 .resolution = 0,
583 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800584
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800585 if (mRawPointerAxes.touchMajor.valid) {
586 mRawPointerAxes.touchMajor.resolution =
587 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700588 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800589 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800590
591 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700592 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800593 if (mRawPointerAxes.touchMinor.valid) {
594 mRawPointerAxes.touchMinor.resolution =
595 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700596 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800597 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800598
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700599 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
600 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
601 .source = mSource,
602 .min = 0,
603 .max = diagonalSize,
604 .flat = 0,
605 .fuzz = 0,
606 .resolution = 0,
607 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800608 if (mRawPointerAxes.toolMajor.valid) {
609 mRawPointerAxes.toolMajor.resolution =
610 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700611 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800612 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800613
614 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700615 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800616 if (mRawPointerAxes.toolMinor.valid) {
617 mRawPointerAxes.toolMinor.resolution =
618 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700619 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800620 }
621
622 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700623 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
624 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
625 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
626 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800627 } else {
628 // Support for other calibrations can be added here.
629 ALOGW("%s calibration is not supported for size ranges at the moment. "
630 "Using raw resolution instead",
631 ftl::enum_string(mCalibration.sizeCalibration).c_str());
632 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800633
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700634 mOrientedRanges.size = InputDeviceInfo::MotionRange{
635 .axis = AMOTION_EVENT_AXIS_SIZE,
636 .source = mSource,
637 .min = 0,
638 .max = 1.0,
639 .flat = 0,
640 .fuzz = 0,
641 .resolution = 0,
642 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800643}
644
645void TouchInputMapper::initializeOrientedRanges() {
646 // Configure X and Y factors.
647 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
648 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
649 mXPrecision = 1.0f / mXScale;
650 mYPrecision = 1.0f / mYScale;
651
652 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
653 mOrientedRanges.x.source = mSource;
654 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
655 mOrientedRanges.y.source = mSource;
656
657 // Scale factor for terms that are not oriented in a particular axis.
658 // If the pixels are square then xScale == yScale otherwise we fake it
659 // by choosing an average.
660 mGeometricScale = avg(mXScale, mYScale);
661
662 initializeSizeRanges();
663
664 // Pressure factors.
665 mPressureScale = 0;
666 float pressureMax = 1.0;
667 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
668 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700669 if (mCalibration.pressureScale) {
670 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800671 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
672 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
673 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
674 }
675 }
676
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700677 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
678 .axis = AMOTION_EVENT_AXIS_PRESSURE,
679 .source = mSource,
680 .min = 0,
681 .max = pressureMax,
682 .flat = 0,
683 .fuzz = 0,
684 .resolution = 0,
685 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800686
687 // Tilt
688 mTiltXCenter = 0;
689 mTiltXScale = 0;
690 mTiltYCenter = 0;
691 mTiltYScale = 0;
692 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
693 if (mHaveTilt) {
694 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
695 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
696 mTiltXScale = M_PI / 180;
697 mTiltYScale = M_PI / 180;
698
699 if (mRawPointerAxes.tiltX.resolution) {
700 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
701 }
702 if (mRawPointerAxes.tiltY.resolution) {
703 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
704 }
705
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700706 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
707 .axis = AMOTION_EVENT_AXIS_TILT,
708 .source = mSource,
709 .min = 0,
710 .max = M_PI_2,
711 .flat = 0,
712 .fuzz = 0,
713 .resolution = 0,
714 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800715 }
716
717 // Orientation
718 mOrientationScale = 0;
719 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700720 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
721 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
722 .source = mSource,
723 .min = -M_PI,
724 .max = M_PI,
725 .flat = 0,
726 .fuzz = 0,
727 .resolution = 0,
728 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800729
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800730 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
731 if (mCalibration.orientationCalibration ==
732 Calibration::OrientationCalibration::INTERPOLATED) {
733 if (mRawPointerAxes.orientation.valid) {
734 if (mRawPointerAxes.orientation.maxValue > 0) {
735 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
736 } else if (mRawPointerAxes.orientation.minValue < 0) {
737 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
738 } else {
739 mOrientationScale = 0;
740 }
741 }
742 }
743
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700744 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
745 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
746 .source = mSource,
747 .min = -M_PI_2,
748 .max = M_PI_2,
749 .flat = 0,
750 .fuzz = 0,
751 .resolution = 0,
752 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800753 }
754
755 // Distance
756 mDistanceScale = 0;
757 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
758 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700759 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800760 }
761
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700762 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800763
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700764 .axis = AMOTION_EVENT_AXIS_DISTANCE,
765 .source = mSource,
766 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
767 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
768 .flat = 0,
769 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
770 .resolution = 0,
771 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800772 }
773
774 // Compute oriented precision, scales and ranges.
775 // Note that the maximum value reported is an inclusive maximum value so it is one
776 // unit less than the total width or height of the display.
777 switch (mInputDeviceOrientation) {
778 case DISPLAY_ORIENTATION_90:
779 case DISPLAY_ORIENTATION_270:
780 mOrientedXPrecision = mYPrecision;
781 mOrientedYPrecision = mXPrecision;
782
783 mOrientedRanges.x.min = 0;
784 mOrientedRanges.x.max = mDisplayHeight - 1;
785 mOrientedRanges.x.flat = 0;
786 mOrientedRanges.x.fuzz = 0;
787 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
788
789 mOrientedRanges.y.min = 0;
790 mOrientedRanges.y.max = mDisplayWidth - 1;
791 mOrientedRanges.y.flat = 0;
792 mOrientedRanges.y.fuzz = 0;
793 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
794 break;
795
796 default:
797 mOrientedXPrecision = mXPrecision;
798 mOrientedYPrecision = mYPrecision;
799
800 mOrientedRanges.x.min = 0;
801 mOrientedRanges.x.max = mDisplayWidth - 1;
802 mOrientedRanges.x.flat = 0;
803 mOrientedRanges.x.fuzz = 0;
804 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
805
806 mOrientedRanges.y.min = 0;
807 mOrientedRanges.y.max = mDisplayHeight - 1;
808 mOrientedRanges.y.flat = 0;
809 mOrientedRanges.y.fuzz = 0;
810 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
811 break;
812 }
813}
814
Prabir Pradhan1728b212021-10-19 16:00:03 -0700815void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000816 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700817
818 resolveExternalStylusPresence();
819
820 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100821 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000822 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700823 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100824 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700825 if (hasStylus()) {
826 mSource |= AINPUT_SOURCE_STYLUS;
827 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800828 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700829 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100830 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700831 if (hasStylus()) {
832 mSource |= AINPUT_SOURCE_STYLUS;
833 }
834 if (hasExternalStylus()) {
835 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
836 }
Michael Wright227c5542020-07-02 18:30:52 +0100837 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700838 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100839 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700840 } else {
841 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100842 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700843 }
844
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000845 const std::optional<DisplayViewport> newViewportOpt = findViewport();
846
847 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700848 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
849 ALOGW("Touch device '%s' did not report support for X or Y axis! "
850 "The device will be inoperable.",
851 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100852 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000853 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700854 ALOGI("Touch device '%s' could not query the properties of its associated "
855 "display. The device will be inoperable until the display size "
856 "becomes available.",
857 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100858 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000859 } else if (!newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000860 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
861 getDeviceName().c_str(), getDeviceId());
862 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000863 }
864
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700865 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700866 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
867 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000868 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
869 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
870 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
871 const float rawMeanResolution =
872 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700873
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000874 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
875 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700876 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700877 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000878 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
879 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
880 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700881
Michael Wright227c5542020-07-02 18:30:52 +0100882 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700883 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700884 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
885 int32_t naturalPhysicalLeft, naturalPhysicalTop;
886 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700887
Prabir Pradhan1728b212021-10-19 16:00:03 -0700888 // Apply the inverse of the input device orientation so that the input device is
889 // configured in the same orientation as the viewport. The input device orientation will
890 // be re-applied by mInputDeviceOrientation.
891 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700892 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700893 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700894 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700895 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
896 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800897 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700898 naturalPhysicalTop = mViewport.physicalLeft;
899 naturalDeviceWidth = mViewport.deviceHeight;
900 naturalDeviceHeight = mViewport.deviceWidth;
901 break;
902 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
904 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
905 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
906 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
907 naturalDeviceWidth = mViewport.deviceWidth;
908 naturalDeviceHeight = mViewport.deviceHeight;
909 break;
910 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
912 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
913 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800914 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700915 naturalDeviceWidth = mViewport.deviceHeight;
916 naturalDeviceHeight = mViewport.deviceWidth;
917 break;
918 case DISPLAY_ORIENTATION_0:
919 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700920 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
921 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
922 naturalPhysicalLeft = mViewport.physicalLeft;
923 naturalPhysicalTop = mViewport.physicalTop;
924 naturalDeviceWidth = mViewport.deviceWidth;
925 naturalDeviceHeight = mViewport.deviceHeight;
926 break;
927 }
928
929 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
930 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
931 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
932 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
933 }
934
935 mPhysicalWidth = naturalPhysicalWidth;
936 mPhysicalHeight = naturalPhysicalHeight;
937 mPhysicalLeft = naturalPhysicalLeft;
938 mPhysicalTop = naturalPhysicalTop;
939
Prabir Pradhan1728b212021-10-19 16:00:03 -0700940 const int32_t oldDisplayWidth = mDisplayWidth;
941 const int32_t oldDisplayHeight = mDisplayHeight;
942 mDisplayWidth = naturalDeviceWidth;
943 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700944
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000945 // InputReader works in the un-rotated display coordinate space, so we don't need to do
946 // anything if the device is already orientation-aware. If the device is not
947 // orientation-aware, then we need to apply the inverse rotation of the display so that
948 // when the display rotation is applied later as a part of the per-window transform, we
949 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700950 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000951 ? DISPLAY_ORIENTATION_0
952 : getInverseRotation(mViewport.orientation);
953 // For orientation-aware devices that work in the un-rotated coordinate space, the
954 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000955 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
956 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
957 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700958
959 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700960 mInputDeviceOrientation =
961 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700962 } else {
963 mPhysicalWidth = rawWidth;
964 mPhysicalHeight = rawHeight;
965 mPhysicalLeft = 0;
966 mPhysicalTop = 0;
967
Prabir Pradhan1728b212021-10-19 16:00:03 -0700968 mDisplayWidth = rawWidth;
969 mDisplayHeight = rawHeight;
970 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700971 }
972 }
973
974 // If moving between pointer modes, need to reset some state.
975 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
976 if (deviceModeChanged) {
977 mOrientedRanges.clear();
978 }
979
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800980 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
981 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100982 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800983 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000984 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
985 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800986 if (mPointerController == nullptr) {
987 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700988 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000989 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800990 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
991 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700992 } else {
lilinnandef700b2022-06-17 19:32:01 +0800993 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
994 !mConfig.showTouches) {
995 mPointerController->clearSpots();
996 }
Michael Wright17db18e2020-06-26 20:51:44 +0100997 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700998 }
999
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001000 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001001 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1002 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001003 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1004 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001005
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001006 configureVirtualKeys();
1007
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001008 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001009
1010 // Location
1011 updateAffineTransformation();
1012
Michael Wright227c5542020-07-02 18:30:52 +01001013 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001014 // Compute pointer gesture detection parameters.
1015 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001016 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001017
1018 // Scale movements such that one whole swipe of the touch pad covers a
1019 // given area relative to the diagonal size of the display when no acceleration
1020 // is applied.
1021 // Assume that the touch pad has a square aspect ratio such that movements in
1022 // X and Y of the same number of raw units cover the same physical distance.
1023 mPointerXMovementScale =
1024 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1025 mPointerYMovementScale = mPointerXMovementScale;
1026
1027 // Scale zooms to cover a smaller range of the display than movements do.
1028 // This value determines the area around the pointer that is affected by freeform
1029 // pointer gestures.
1030 mPointerXZoomScale =
1031 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1032 mPointerYZoomScale = mPointerXZoomScale;
1033
HQ Liue6983c72022-04-19 22:14:56 +00001034 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1035 // axis is non positive value.
1036 const float minFreeformGestureWidth =
1037 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1038
1039 mPointerGestureMaxSwipeWidth =
1040 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1041 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001042 }
1043
1044 // Inform the dispatcher about the changes.
1045 *outResetNeeded = true;
1046 bumpGeneration();
1047 }
1048}
1049
Prabir Pradhan1728b212021-10-19 16:00:03 -07001050void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001051 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001052 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1053 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001054 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1055 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1056 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1057 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001058 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059}
1060
1061void TouchInputMapper::configureVirtualKeys() {
1062 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001063 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001064
1065 mVirtualKeys.clear();
1066
1067 if (virtualKeyDefinitions.size() == 0) {
1068 return;
1069 }
1070
1071 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1072 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1073 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1074 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1075
1076 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1077 VirtualKey virtualKey;
1078
1079 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1080 int32_t keyCode;
1081 int32_t dummyKeyMetaState;
1082 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001083 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1084 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001085 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1086 continue; // drop the key
1087 }
1088
1089 virtualKey.keyCode = keyCode;
1090 virtualKey.flags = flags;
1091
1092 // convert the key definition's display coordinates into touch coordinates for a hit box
1093 int32_t halfWidth = virtualKeyDefinition.width / 2;
1094 int32_t halfHeight = virtualKeyDefinition.height / 2;
1095
1096 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001097 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001098 touchScreenLeft;
1099 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001100 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001101 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001102 virtualKey.hitTop =
1103 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001105 virtualKey.hitBottom =
1106 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001107 touchScreenTop;
1108 mVirtualKeys.push_back(virtualKey);
1109 }
1110}
1111
1112void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1113 if (!mVirtualKeys.empty()) {
1114 dump += INDENT3 "Virtual Keys:\n";
1115
1116 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1117 const VirtualKey& virtualKey = mVirtualKeys[i];
1118 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1119 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1120 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1121 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1122 }
1123 }
1124}
1125
1126void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001127 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128 Calibration& out = mCalibration;
1129
1130 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001131 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001132 std::string sizeCalibrationString;
1133 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001134 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001135 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001137 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001139 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001140 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001141 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001145 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 }
1147 }
1148
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001149 float sizeScale;
1150
1151 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1152 out.sizeScale = sizeScale;
1153 }
1154 float sizeBias;
1155 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1156 out.sizeBias = sizeBias;
1157 }
1158 bool sizeIsSummed;
1159 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1160 out.sizeIsSummed = sizeIsSummed;
1161 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001162
1163 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001164 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001165 std::string pressureCalibrationString;
1166 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001172 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001173 } else if (pressureCalibrationString != "default") {
1174 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001175 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 }
1177 }
1178
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001179 float pressureScale;
1180 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1181 out.pressureScale = pressureScale;
1182 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183
1184 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001186 std::string orientationCalibrationString;
1187 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001193 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001194 } else if (orientationCalibrationString != "default") {
1195 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001196 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 }
1198 }
1199
1200 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001202 std::string distanceCalibrationString;
1203 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001206 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 } else if (distanceCalibrationString != "default") {
1209 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001210 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 }
1212 }
1213
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001214 float distanceScale;
1215 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1216 out.distanceScale = distanceScale;
1217 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001218
Michael Wright227c5542020-07-02 18:30:52 +01001219 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001220 std::string coverageCalibrationString;
1221 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001223 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001225 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226 } else if (coverageCalibrationString != "default") {
1227 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001228 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230 }
1231}
1232
1233void TouchInputMapper::resolveCalibration() {
1234 // Size
1235 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001236 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1237 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 }
1239 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001240 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242
1243 // Pressure
1244 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001245 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1246 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 }
1248 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001249 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251
1252 // Orientation
1253 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001254 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1255 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256 }
1257 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001258 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260
1261 // Distance
1262 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001263 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1264 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 }
1266 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001267 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 }
1269
1270 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001271 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1272 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 }
1274}
1275
1276void TouchInputMapper::dumpCalibration(std::string& dump) {
1277 dump += INDENT3 "Calibration:\n";
1278
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001279 dump += INDENT4 "touch.size.calibration: ";
1280 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001282 if (mCalibration.sizeScale) {
1283 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001286 if (mCalibration.sizeBias) {
1287 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 }
1289
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001290 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001292 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 }
1294
1295 // Pressure
1296 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001297 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += INDENT4 "touch.pressure.calibration: none\n";
1299 break;
Michael Wright227c5542020-07-02 18:30:52 +01001300 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += INDENT4 "touch.pressure.calibration: physical\n";
1302 break;
Michael Wright227c5542020-07-02 18:30:52 +01001303 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1305 break;
1306 default:
1307 ALOG_ASSERT(false);
1308 }
1309
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001310 if (mCalibration.pressureScale) {
1311 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 }
1313
1314 // Orientation
1315 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001316 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 dump += INDENT4 "touch.orientation.calibration: none\n";
1318 break;
Michael Wright227c5542020-07-02 18:30:52 +01001319 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1321 break;
Michael Wright227c5542020-07-02 18:30:52 +01001322 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001323 dump += INDENT4 "touch.orientation.calibration: vector\n";
1324 break;
1325 default:
1326 ALOG_ASSERT(false);
1327 }
1328
1329 // Distance
1330 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.distance.calibration: none\n";
1333 break;
Michael Wright227c5542020-07-02 18:30:52 +01001334 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001335 dump += INDENT4 "touch.distance.calibration: scaled\n";
1336 break;
1337 default:
1338 ALOG_ASSERT(false);
1339 }
1340
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001341 if (mCalibration.distanceScale) {
1342 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 }
1344
1345 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001346 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001347 dump += INDENT4 "touch.coverage.calibration: none\n";
1348 break;
Michael Wright227c5542020-07-02 18:30:52 +01001349 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350 dump += INDENT4 "touch.coverage.calibration: box\n";
1351 break;
1352 default:
1353 ALOG_ASSERT(false);
1354 }
1355}
1356
1357void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1358 dump += INDENT3 "Affine Transformation:\n";
1359
1360 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1361 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1362 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1363 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1364 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1365 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1366}
1367
1368void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001369 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001370 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001371}
1372
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001373std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001374 std::list<NotifyArgs> out = cancelTouch(when, when);
1375 updateTouchSpots();
1376
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001377 mCursorButtonAccumulator.reset(getDeviceContext());
1378 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001379 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001380
1381 mPointerVelocityControl.reset();
1382 mWheelXVelocityControl.reset();
1383 mWheelYVelocityControl.reset();
1384
1385 mRawStatesPending.clear();
1386 mCurrentRawState.clear();
1387 mCurrentCookedState.clear();
1388 mLastRawState.clear();
1389 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001390 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391 mSentHoverEnter = false;
1392 mHavePointerIds = false;
1393 mCurrentMotionAborted = false;
1394 mDownTime = 0;
1395
1396 mCurrentVirtualKey.down = false;
1397
1398 mPointerGesture.reset();
1399 mPointerSimple.reset();
1400 resetExternalStylus();
1401
1402 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001403 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001404 mPointerController->clearSpots();
1405 }
1406
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001407 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001408}
1409
1410void TouchInputMapper::resetExternalStylus() {
1411 mExternalStylusState.clear();
1412 mExternalStylusId = -1;
1413 mExternalStylusFusionTimeout = LLONG_MAX;
1414 mExternalStylusDataPending = false;
1415}
1416
1417void TouchInputMapper::clearStylusDataPendingFlags() {
1418 mExternalStylusDataPending = false;
1419 mExternalStylusFusionTimeout = LLONG_MAX;
1420}
1421
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001422std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423 mCursorButtonAccumulator.process(rawEvent);
1424 mCursorScrollAccumulator.process(rawEvent);
1425 mTouchButtonAccumulator.process(rawEvent);
1426
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001427 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001428 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001429 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001430 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001431 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001432}
1433
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001434std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1435 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001436 if (mDeviceMode == DeviceMode::DISABLED) {
1437 // Only save the last pending state when the device is disabled.
1438 mRawStatesPending.clear();
1439 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440 // Push a new state.
1441 mRawStatesPending.emplace_back();
1442
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001443 RawState& next = mRawStatesPending.back();
1444 next.clear();
1445 next.when = when;
1446 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447
1448 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001449 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001450 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1451
1452 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001453 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1454 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455 mCursorScrollAccumulator.finishSync();
1456
1457 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001458 syncTouch(when, &next);
1459
1460 // The last RawState is the actually second to last, since we just added a new state
1461 const RawState& last =
1462 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001463
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001464 next.when = applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1465 last.when);
1466
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001467 // Assign pointer ids.
1468 if (!mHavePointerIds) {
1469 assignPointerIds(last, next);
1470 }
1471
Harry Cutts45483602022-08-24 14:36:48 +00001472 ALOGD_IF(DEBUG_RAW_EVENTS,
1473 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1474 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1475 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1476 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1477 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1478 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479
Arthur Hung9ad18942021-06-19 02:04:46 +00001480 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1481 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1482 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1483 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1484 next.rawPointerData.hoveringIdBits.value);
1485 }
1486
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001487 out += processRawTouches(false /*timeout*/);
1488 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001489}
1490
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001491std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1492 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001493 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001494 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001495 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496 }
1497
1498 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1499 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1500 // touching the current state will only observe the events that have been dispatched to the
1501 // rest of the pipeline.
1502 const size_t N = mRawStatesPending.size();
1503 size_t count;
1504 for (count = 0; count < N; count++) {
1505 const RawState& next = mRawStatesPending[count];
1506
1507 // A failure to assign the stylus id means that we're waiting on stylus data
1508 // and so should defer the rest of the pipeline.
1509 if (assignExternalStylusId(next, timeout)) {
1510 break;
1511 }
1512
1513 // All ready to go.
1514 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001515 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001516 if (mCurrentRawState.when < mLastRawState.when) {
1517 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001518 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001519 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001520 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521 }
1522 if (count != 0) {
1523 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1524 }
1525
1526 if (mExternalStylusDataPending) {
1527 if (timeout) {
1528 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1529 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001530 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001531 ALOGD_IF(DEBUG_STYLUS_FUSION,
1532 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001533 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001534 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001535 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1536 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1537 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1538 }
1539 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001540 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001541}
1542
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001543std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1544 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001545 // Always start with a clean state.
1546 mCurrentCookedState.clear();
1547
1548 // Apply stylus buttons to current raw state.
1549 applyExternalStylusButtonState(when);
1550
1551 // Handle policy on initial down or hover events.
1552 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1553 mCurrentRawState.rawPointerData.pointerCount != 0;
1554
1555 uint32_t policyFlags = 0;
1556 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1557 if (initialDown || buttonsPressed) {
1558 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001559 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001560 getContext()->fadePointer();
1561 }
1562
1563 if (mParameters.wake) {
1564 policyFlags |= POLICY_FLAG_WAKE;
1565 }
1566 }
1567
1568 // Consume raw off-screen touches before cooking pointer data.
1569 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001570 bool consumed;
1571 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1572 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001573 mCurrentRawState.rawPointerData.clear();
1574 }
1575
1576 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1577 // with cooked pointer data that has the same ids and indices as the raw data.
1578 // The following code can use either the raw or cooked data, as needed.
1579 cookPointerData();
1580
1581 // Apply stylus pressure to current cooked state.
1582 applyExternalStylusTouchState(when);
1583
1584 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001585 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1586 mSource, mViewport.displayId, policyFlags,
1587 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001588
1589 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001590 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1592 uint32_t id = idBits.clearFirstMarkedBit();
1593 const RawPointerData::Pointer& pointer =
1594 mCurrentRawState.rawPointerData.pointerForId(id);
1595 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1596 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1597 mCurrentCookedState.stylusIdBits.markBit(id);
1598 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1599 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1600 mCurrentCookedState.fingerIdBits.markBit(id);
1601 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1602 mCurrentCookedState.mouseIdBits.markBit(id);
1603 }
1604 }
1605 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1606 uint32_t id = idBits.clearFirstMarkedBit();
1607 const RawPointerData::Pointer& pointer =
1608 mCurrentRawState.rawPointerData.pointerForId(id);
1609 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1610 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1611 mCurrentCookedState.stylusIdBits.markBit(id);
1612 }
1613 }
1614
1615 // Stylus takes precedence over all tools, then mouse, then finger.
1616 PointerUsage pointerUsage = mPointerUsage;
1617 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1618 mCurrentCookedState.mouseIdBits.clear();
1619 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001620 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001621 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1622 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001623 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1625 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001626 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627 }
1628
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001629 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001631 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001632 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001633 out += dispatchButtonRelease(when, readTime, policyFlags);
1634 out += dispatchHoverExit(when, readTime, policyFlags);
1635 out += dispatchTouches(when, readTime, policyFlags);
1636 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1637 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001638 }
1639
1640 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1641 mCurrentMotionAborted = false;
1642 }
1643 }
1644
1645 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001646 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1647 mSource, mViewport.displayId, policyFlags,
1648 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001649
1650 // Clear some transient state.
1651 mCurrentRawState.rawVScroll = 0;
1652 mCurrentRawState.rawHScroll = 0;
1653
1654 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001655 mLastRawState = mCurrentRawState;
1656 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001657 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001658}
1659
Garfield Tanc734e4f2021-01-15 20:01:39 -08001660void TouchInputMapper::updateTouchSpots() {
1661 if (!mConfig.showTouches || mPointerController == nullptr) {
1662 return;
1663 }
1664
1665 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1666 // clear touch spots.
1667 if (mDeviceMode != DeviceMode::DIRECT &&
1668 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1669 return;
1670 }
1671
1672 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1673 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1674
1675 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001676 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1677 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001678 mCurrentCookedState.cookedPointerData.touchingIdBits,
1679 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001680}
1681
1682bool TouchInputMapper::isTouchScreen() {
1683 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1684 mParameters.hasAssociatedDisplay;
1685}
1686
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001687void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001688 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001689 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1690 }
1691}
1692
1693void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1694 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1695 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1696
1697 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1698 float pressure = mExternalStylusState.pressure;
1699 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1700 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1701 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1702 }
1703 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1704 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1705
1706 PointerProperties& properties =
1707 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1708 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1709 properties.toolType = mExternalStylusState.toolType;
1710 }
1711 }
1712}
1713
1714bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001715 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001716 return false;
1717 }
1718
1719 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1720 state.rawPointerData.pointerCount != 0;
1721 if (initialDown) {
1722 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001723 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001724 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1725 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001726 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001727 resetExternalStylus();
1728 } else {
1729 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1730 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1731 }
Harry Cutts45483602022-08-24 14:36:48 +00001732 ALOGD_IF(DEBUG_STYLUS_FUSION,
1733 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1734 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001735 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1736 return true;
1737 }
1738 }
1739
1740 // Check if the stylus pointer has gone up.
1741 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001742 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001743 mExternalStylusId = -1;
1744 }
1745
1746 return false;
1747}
1748
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001749std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1750 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001751 if (mDeviceMode == DeviceMode::POINTER) {
1752 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001753 // Since this is a synthetic event, we can consider its latency to be zero
1754 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001755 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001756 }
Michael Wright227c5542020-07-02 18:30:52 +01001757 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001758 if (mExternalStylusFusionTimeout < when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001759 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001760 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1761 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1762 }
1763 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001764 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001765}
1766
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001767std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1768 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001769 mExternalStylusState.copyFrom(state);
1770 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1771 // We're either in the middle of a fused stream of data or we're waiting on data before
1772 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1773 // data.
1774 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001775 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001776 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001777 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001778}
1779
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001780std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1781 uint32_t policyFlags, bool& outConsumed) {
1782 outConsumed = false;
1783 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001784 // Check for release of a virtual key.
1785 if (mCurrentVirtualKey.down) {
1786 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1787 // Pointer went up while virtual key was down.
1788 mCurrentVirtualKey.down = false;
1789 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001790 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1791 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1792 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001793 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1794 AKEY_EVENT_FLAG_FROM_SYSTEM |
1795 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001796 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001797 outConsumed = true;
1798 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001799 }
1800
1801 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1802 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1803 const RawPointerData::Pointer& pointer =
1804 mCurrentRawState.rawPointerData.pointerForId(id);
1805 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1806 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1807 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001808 outConsumed = true;
1809 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001810 }
1811 }
1812
1813 // Pointer left virtual key area or another pointer also went down.
1814 // Send key cancellation but do not consume the touch yet.
1815 // This is useful when the user swipes through from the virtual key area
1816 // into the main display surface.
1817 mCurrentVirtualKey.down = false;
1818 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001819 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1820 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001821 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1822 AKEY_EVENT_FLAG_FROM_SYSTEM |
1823 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1824 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001825 }
1826 }
1827
1828 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1829 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1830 // Pointer just went down. Check for virtual key press or off-screen touches.
1831 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1832 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001833 // Skip checking whether the pointer is inside the physical frame if the device is in
1834 // unscaled mode.
1835 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1836 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001837 // If exactly one pointer went down, check for virtual key hit.
1838 // Otherwise we will drop the entire stroke.
1839 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1840 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1841 if (virtualKey) {
1842 mCurrentVirtualKey.down = true;
1843 mCurrentVirtualKey.downTime = when;
1844 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1845 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1846 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001847 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1848 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001849
1850 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001851 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1852 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1853 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001854 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1855 AKEY_EVENT_ACTION_DOWN,
1856 AKEY_EVENT_FLAG_FROM_SYSTEM |
1857 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001858 }
1859 }
1860 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001861 outConsumed = true;
1862 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001863 }
1864 }
1865
1866 // Disable all virtual key touches that happen within a short time interval of the
1867 // most recent touch within the screen area. The idea is to filter out stray
1868 // virtual key presses when interacting with the touch screen.
1869 //
1870 // Problems we're trying to solve:
1871 //
1872 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1873 // virtual key area that is implemented by a separate touch panel and accidentally
1874 // triggers a virtual key.
1875 //
1876 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1877 // area and accidentally triggers a virtual key. This often happens when virtual keys
1878 // are layed out below the screen near to where the on screen keyboard's space bar
1879 // is displayed.
1880 if (mConfig.virtualKeyQuietTime > 0 &&
1881 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001882 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001883 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001884 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001885}
1886
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001887NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1888 uint32_t policyFlags, int32_t keyEventAction,
1889 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001890 int32_t keyCode = mCurrentVirtualKey.keyCode;
1891 int32_t scanCode = mCurrentVirtualKey.scanCode;
1892 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001893 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001894 policyFlags |= POLICY_FLAG_VIRTUAL;
1895
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001896 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1897 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1898 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001899}
1900
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001901std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1902 uint32_t policyFlags) {
1903 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001904 if (mCurrentMotionAborted) {
1905 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001906 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001907 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001908 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1909 if (!currentIdBits.isEmpty()) {
1910 int32_t metaState = getContext()->getGlobalMetaState();
1911 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001912 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001913 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1914 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001915 mCurrentCookedState.cookedPointerData.pointerProperties,
1916 mCurrentCookedState.cookedPointerData.pointerCoords,
1917 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1918 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1919 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001920 mCurrentMotionAborted = true;
1921 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001922 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001923}
1924
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001925// Updates pointer coords and properties for pointers with specified ids that have moved.
1926// Returns true if any of them changed.
1927static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1928 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1929 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1930 BitSet32 idBits) {
1931 bool changed = false;
1932 while (!idBits.isEmpty()) {
1933 uint32_t id = idBits.clearFirstMarkedBit();
1934 uint32_t inIndex = inIdToIndex[id];
1935 uint32_t outIndex = outIdToIndex[id];
1936
1937 const PointerProperties& curInProperties = inProperties[inIndex];
1938 const PointerCoords& curInCoords = inCoords[inIndex];
1939 PointerProperties& curOutProperties = outProperties[outIndex];
1940 PointerCoords& curOutCoords = outCoords[outIndex];
1941
1942 if (curInProperties != curOutProperties) {
1943 curOutProperties.copyFrom(curInProperties);
1944 changed = true;
1945 }
1946
1947 if (curInCoords != curOutCoords) {
1948 curOutCoords.copyFrom(curInCoords);
1949 changed = true;
1950 }
1951 }
1952 return changed;
1953}
1954
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001955std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1956 uint32_t policyFlags) {
1957 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001958 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1959 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1960 int32_t metaState = getContext()->getGlobalMetaState();
1961 int32_t buttonState = mCurrentCookedState.buttonState;
1962
1963 if (currentIdBits == lastIdBits) {
1964 if (!currentIdBits.isEmpty()) {
1965 // No pointer id changes so this is a move event.
1966 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001967 out.push_back(
1968 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1969 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1970 mCurrentCookedState.cookedPointerData.pointerProperties,
1971 mCurrentCookedState.cookedPointerData.pointerCoords,
1972 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1973 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1974 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001975 }
1976 } else {
1977 // There may be pointers going up and pointers going down and pointers moving
1978 // all at the same time.
1979 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1980 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1981 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1982 BitSet32 dispatchedIdBits(lastIdBits.value);
1983
1984 // Update last coordinates of pointers that have moved so that we observe the new
1985 // pointer positions at the same time as other pointers that have just gone up.
1986 bool moveNeeded =
1987 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1988 mCurrentCookedState.cookedPointerData.pointerCoords,
1989 mCurrentCookedState.cookedPointerData.idToIndex,
1990 mLastCookedState.cookedPointerData.pointerProperties,
1991 mLastCookedState.cookedPointerData.pointerCoords,
1992 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1993 if (buttonState != mLastCookedState.buttonState) {
1994 moveNeeded = true;
1995 }
1996
1997 // Dispatch pointer up events.
1998 while (!upIdBits.isEmpty()) {
1999 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002000 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002001 if (isCanceled) {
2002 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2003 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002004 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2005 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2006 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2007 buttonState, 0,
2008 mLastCookedState.cookedPointerData.pointerProperties,
2009 mLastCookedState.cookedPointerData.pointerCoords,
2010 mLastCookedState.cookedPointerData.idToIndex,
2011 dispatchedIdBits, upId, mOrientedXPrecision,
2012 mOrientedYPrecision, mDownTime,
2013 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002014 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002015 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002016 }
2017
2018 // Dispatch move events if any of the remaining pointers moved from their old locations.
2019 // Although applications receive new locations as part of individual pointer up
2020 // events, they do not generally handle them except when presented in a move event.
2021 if (moveNeeded && !moveIdBits.isEmpty()) {
2022 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002023 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2024 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2025 mCurrentCookedState.cookedPointerData.pointerProperties,
2026 mCurrentCookedState.cookedPointerData.pointerCoords,
2027 mCurrentCookedState.cookedPointerData.idToIndex,
2028 dispatchedIdBits, -1, mOrientedXPrecision,
2029 mOrientedYPrecision, mDownTime,
2030 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002031 }
2032
2033 // Dispatch pointer down events using the new pointer locations.
2034 while (!downIdBits.isEmpty()) {
2035 uint32_t downId = downIdBits.clearFirstMarkedBit();
2036 dispatchedIdBits.markBit(downId);
2037
2038 if (dispatchedIdBits.count() == 1) {
2039 // First pointer is going down. Set down time.
2040 mDownTime = when;
2041 }
2042
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002043 out.push_back(
2044 dispatchMotion(when, readTime, policyFlags, mSource,
2045 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2046 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2047 mCurrentCookedState.cookedPointerData.pointerCoords,
2048 mCurrentCookedState.cookedPointerData.idToIndex,
2049 dispatchedIdBits, downId, mOrientedXPrecision,
2050 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002051 }
2052 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002053 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002054}
2055
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002056std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2057 uint32_t policyFlags) {
2058 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002059 if (mSentHoverEnter &&
2060 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2061 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2062 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002063 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2064 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2065 mLastCookedState.buttonState, 0,
2066 mLastCookedState.cookedPointerData.pointerProperties,
2067 mLastCookedState.cookedPointerData.pointerCoords,
2068 mLastCookedState.cookedPointerData.idToIndex,
2069 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2070 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2071 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002072 mSentHoverEnter = false;
2073 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002074 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002075}
2076
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002077std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2078 uint32_t policyFlags) {
2079 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002080 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2081 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2082 int32_t metaState = getContext()->getGlobalMetaState();
2083 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002084 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2085 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2086 mCurrentRawState.buttonState, 0,
2087 mCurrentCookedState.cookedPointerData.pointerProperties,
2088 mCurrentCookedState.cookedPointerData.pointerCoords,
2089 mCurrentCookedState.cookedPointerData.idToIndex,
2090 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2091 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2092 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002093 mSentHoverEnter = true;
2094 }
2095
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002096 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2097 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2098 mCurrentRawState.buttonState, 0,
2099 mCurrentCookedState.cookedPointerData.pointerProperties,
2100 mCurrentCookedState.cookedPointerData.pointerCoords,
2101 mCurrentCookedState.cookedPointerData.idToIndex,
2102 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2103 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2104 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002105 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002106 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002107}
2108
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002109std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2110 uint32_t policyFlags) {
2111 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002112 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2113 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2114 const int32_t metaState = getContext()->getGlobalMetaState();
2115 int32_t buttonState = mLastCookedState.buttonState;
2116 while (!releasedButtons.isEmpty()) {
2117 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2118 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002119 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2120 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2121 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002122 mLastCookedState.cookedPointerData.pointerProperties,
2123 mLastCookedState.cookedPointerData.pointerCoords,
2124 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002125 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2126 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002127 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002128 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002129}
2130
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002131std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2132 uint32_t policyFlags) {
2133 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002134 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2135 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2136 const int32_t metaState = getContext()->getGlobalMetaState();
2137 int32_t buttonState = mLastCookedState.buttonState;
2138 while (!pressedButtons.isEmpty()) {
2139 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2140 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002141 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2142 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2143 buttonState, 0,
2144 mCurrentCookedState.cookedPointerData.pointerProperties,
2145 mCurrentCookedState.cookedPointerData.pointerCoords,
2146 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2147 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2148 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002149 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002150 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002151}
2152
2153const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2154 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2155 return cookedPointerData.touchingIdBits;
2156 }
2157 return cookedPointerData.hoveringIdBits;
2158}
2159
2160void TouchInputMapper::cookPointerData() {
2161 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2162
2163 mCurrentCookedState.cookedPointerData.clear();
2164 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2165 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2166 mCurrentRawState.rawPointerData.hoveringIdBits;
2167 mCurrentCookedState.cookedPointerData.touchingIdBits =
2168 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002169 mCurrentCookedState.cookedPointerData.canceledIdBits =
2170 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002171
2172 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2173 mCurrentCookedState.buttonState = 0;
2174 } else {
2175 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2176 }
2177
2178 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002179 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002180 for (uint32_t i = 0; i < currentPointerCount; i++) {
2181 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2182
2183 // Size
2184 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2185 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002186 case Calibration::SizeCalibration::GEOMETRIC:
2187 case Calibration::SizeCalibration::DIAMETER:
2188 case Calibration::SizeCalibration::BOX:
2189 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002190 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2191 touchMajor = in.touchMajor;
2192 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2193 toolMajor = in.toolMajor;
2194 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2195 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2196 : in.touchMajor;
2197 } else if (mRawPointerAxes.touchMajor.valid) {
2198 toolMajor = touchMajor = in.touchMajor;
2199 toolMinor = touchMinor =
2200 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2201 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2202 : in.touchMajor;
2203 } else if (mRawPointerAxes.toolMajor.valid) {
2204 touchMajor = toolMajor = in.toolMajor;
2205 touchMinor = toolMinor =
2206 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2207 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2208 : in.toolMajor;
2209 } else {
2210 ALOG_ASSERT(false,
2211 "No touch or tool axes. "
2212 "Size calibration should have been resolved to NONE.");
2213 touchMajor = 0;
2214 touchMinor = 0;
2215 toolMajor = 0;
2216 toolMinor = 0;
2217 size = 0;
2218 }
2219
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002220 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002221 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2222 if (touchingCount > 1) {
2223 touchMajor /= touchingCount;
2224 touchMinor /= touchingCount;
2225 toolMajor /= touchingCount;
2226 toolMinor /= touchingCount;
2227 size /= touchingCount;
2228 }
2229 }
2230
Michael Wright227c5542020-07-02 18:30:52 +01002231 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002232 touchMajor *= mGeometricScale;
2233 touchMinor *= mGeometricScale;
2234 toolMajor *= mGeometricScale;
2235 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002236 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002237 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2238 touchMinor = touchMajor;
2239 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2240 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002241 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002242 touchMinor = touchMajor;
2243 toolMinor = toolMajor;
2244 }
2245
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002246 mCalibration.applySizeScaleAndBias(touchMajor);
2247 mCalibration.applySizeScaleAndBias(touchMinor);
2248 mCalibration.applySizeScaleAndBias(toolMajor);
2249 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002250 size *= mSizeScale;
2251 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002252 case Calibration::SizeCalibration::DEFAULT:
2253 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2254 break;
2255 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 touchMajor = 0;
2257 touchMinor = 0;
2258 toolMajor = 0;
2259 toolMinor = 0;
2260 size = 0;
2261 break;
2262 }
2263
2264 // Pressure
2265 float pressure;
2266 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002267 case Calibration::PressureCalibration::PHYSICAL:
2268 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002269 pressure = in.pressure * mPressureScale;
2270 break;
2271 default:
2272 pressure = in.isHovering ? 0 : 1;
2273 break;
2274 }
2275
2276 // Tilt and Orientation
2277 float tilt;
2278 float orientation;
2279 if (mHaveTilt) {
2280 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2281 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2282 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2283 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2284 } else {
2285 tilt = 0;
2286
2287 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002288 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002289 orientation = in.orientation * mOrientationScale;
2290 break;
Michael Wright227c5542020-07-02 18:30:52 +01002291 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2293 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2294 if (c1 != 0 || c2 != 0) {
2295 orientation = atan2f(c1, c2) * 0.5f;
2296 float confidence = hypotf(c1, c2);
2297 float scale = 1.0f + confidence / 16.0f;
2298 touchMajor *= scale;
2299 touchMinor /= scale;
2300 toolMajor *= scale;
2301 toolMinor /= scale;
2302 } else {
2303 orientation = 0;
2304 }
2305 break;
2306 }
2307 default:
2308 orientation = 0;
2309 }
2310 }
2311
2312 // Distance
2313 float distance;
2314 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002315 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002316 distance = in.distance * mDistanceScale;
2317 break;
2318 default:
2319 distance = 0;
2320 }
2321
2322 // Coverage
2323 int32_t rawLeft, rawTop, rawRight, rawBottom;
2324 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002325 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002326 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2327 rawRight = in.toolMinor & 0x0000ffff;
2328 rawBottom = in.toolMajor & 0x0000ffff;
2329 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2330 break;
2331 default:
2332 rawLeft = rawTop = rawRight = rawBottom = 0;
2333 break;
2334 }
2335
2336 // Adjust X,Y coords for device calibration
2337 // TODO: Adjust coverage coords?
2338 float xTransformed = in.x, yTransformed = in.y;
2339 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002340 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002341
Prabir Pradhan1728b212021-10-19 16:00:03 -07002342 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 float left, top, right, bottom;
2344
Prabir Pradhan1728b212021-10-19 16:00:03 -07002345 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002346 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002347 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2348 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2349 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2350 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002352 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002354 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 }
2356 break;
2357 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2359 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002360 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2361 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002363 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002364 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002365 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 }
2367 break;
2368 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2370 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002371 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2372 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002374 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002376 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 }
2378 break;
2379 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002380 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2381 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2382 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2383 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 break;
2385 }
2386
2387 // Write output coords.
2388 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2389 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002390 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2391 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2393 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2394 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2395 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2396 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2397 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2398 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002399 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2402 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2403 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2404 } else {
2405 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2406 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2407 }
2408
Chris Ye364fdb52020-08-05 15:07:56 -07002409 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002410 uint32_t id = in.id;
2411 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2412 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2413 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2414 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2415 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2416 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2417 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2418 }
2419
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 // Write output properties.
2421 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002422 properties.clear();
2423 properties.id = id;
2424 properties.toolType = in.toolType;
2425
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002426 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002428 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429 }
2430}
2431
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002432std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2433 uint32_t policyFlags,
2434 PointerUsage pointerUsage) {
2435 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002437 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002438 mPointerUsage = pointerUsage;
2439 }
2440
2441 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002442 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002443 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002444 break;
Michael Wright227c5542020-07-02 18:30:52 +01002445 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002446 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002447 break;
Michael Wright227c5542020-07-02 18:30:52 +01002448 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002449 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 break;
Michael Wright227c5542020-07-02 18:30:52 +01002451 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452 break;
2453 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002454 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002455}
2456
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002457std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2458 uint32_t policyFlags) {
2459 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002461 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002462 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 break;
Michael Wright227c5542020-07-02 18:30:52 +01002464 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002465 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 break;
Michael Wright227c5542020-07-02 18:30:52 +01002467 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002468 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 break;
Michael Wright227c5542020-07-02 18:30:52 +01002470 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002471 break;
2472 }
2473
Michael Wright227c5542020-07-02 18:30:52 +01002474 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002475 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476}
2477
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002478std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2479 uint32_t policyFlags,
2480 bool isTimeout) {
2481 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002482 // Update current gesture coordinates.
2483 bool cancelPreviousGesture, finishPreviousGesture;
2484 bool sendEvents =
2485 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2486 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002487 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002488 }
2489 if (finishPreviousGesture) {
2490 cancelPreviousGesture = false;
2491 }
2492
2493 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002494 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002495 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496 if (finishPreviousGesture || cancelPreviousGesture) {
2497 mPointerController->clearSpots();
2498 }
2499
Michael Wright227c5542020-07-02 18:30:52 +01002500 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002501 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2502 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002503 mPointerGesture.currentGestureIdBits,
2504 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002505 }
2506 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002507 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002508 }
2509
2510 // Show or hide the pointer if needed.
2511 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002512 case PointerGesture::Mode::NEUTRAL:
2513 case PointerGesture::Mode::QUIET:
2514 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2515 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002517 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002518 }
2519 break;
Michael Wright227c5542020-07-02 18:30:52 +01002520 case PointerGesture::Mode::TAP:
2521 case PointerGesture::Mode::TAP_DRAG:
2522 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2523 case PointerGesture::Mode::HOVER:
2524 case PointerGesture::Mode::PRESS:
2525 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002526 // Unfade the pointer when the current gesture manipulates the
2527 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002528 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002529 break;
Michael Wright227c5542020-07-02 18:30:52 +01002530 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002531 // Fade the pointer when the current gesture manipulates a different
2532 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002533 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002534 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002536 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002537 }
2538 break;
2539 }
2540
2541 // Send events!
2542 int32_t metaState = getContext()->getGlobalMetaState();
2543 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002544 const MotionClassification classification =
2545 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2546 ? MotionClassification::TWO_FINGER_SWIPE
2547 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002548
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002549 uint32_t flags = 0;
2550
2551 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2552 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2553 }
2554
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002555 // Update last coordinates of pointers that have moved so that we observe the new
2556 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002557 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2558 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2559 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2560 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2561 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2562 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002563 bool moveNeeded = false;
2564 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2565 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2566 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2567 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2568 mPointerGesture.lastGestureIdBits.value);
2569 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2570 mPointerGesture.currentGestureCoords,
2571 mPointerGesture.currentGestureIdToIndex,
2572 mPointerGesture.lastGestureProperties,
2573 mPointerGesture.lastGestureCoords,
2574 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2575 if (buttonState != mLastCookedState.buttonState) {
2576 moveNeeded = true;
2577 }
2578 }
2579
2580 // Send motion events for all pointers that went up or were canceled.
2581 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2582 if (!dispatchedGestureIdBits.isEmpty()) {
2583 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002584 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002585 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002586 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002587 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2588 mPointerGesture.lastGestureProperties,
2589 mPointerGesture.lastGestureCoords,
2590 mPointerGesture.lastGestureIdToIndex,
2591 dispatchedGestureIdBits, -1, 0, 0,
2592 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002593
2594 dispatchedGestureIdBits.clear();
2595 } else {
2596 BitSet32 upGestureIdBits;
2597 if (finishPreviousGesture) {
2598 upGestureIdBits = dispatchedGestureIdBits;
2599 } else {
2600 upGestureIdBits.value =
2601 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2602 }
2603 while (!upGestureIdBits.isEmpty()) {
2604 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2605
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002606 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2607 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2608 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2609 mPointerGesture.lastGestureProperties,
2610 mPointerGesture.lastGestureCoords,
2611 mPointerGesture.lastGestureIdToIndex,
2612 dispatchedGestureIdBits, id, 0, 0,
2613 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002614
2615 dispatchedGestureIdBits.clearBit(id);
2616 }
2617 }
2618 }
2619
2620 // Send motion events for all pointers that moved.
2621 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002622 out.push_back(
2623 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2624 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2625 mPointerGesture.currentGestureProperties,
2626 mPointerGesture.currentGestureCoords,
2627 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2628 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002629 }
2630
2631 // Send motion events for all pointers that went down.
2632 if (down) {
2633 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2634 ~dispatchedGestureIdBits.value);
2635 while (!downGestureIdBits.isEmpty()) {
2636 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2637 dispatchedGestureIdBits.markBit(id);
2638
2639 if (dispatchedGestureIdBits.count() == 1) {
2640 mPointerGesture.downTime = when;
2641 }
2642
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002643 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2644 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2645 buttonState, 0, mPointerGesture.currentGestureProperties,
2646 mPointerGesture.currentGestureCoords,
2647 mPointerGesture.currentGestureIdToIndex,
2648 dispatchedGestureIdBits, id, 0, 0,
2649 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002650 }
2651 }
2652
2653 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002654 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002655 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2656 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2657 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2658 mPointerGesture.currentGestureProperties,
2659 mPointerGesture.currentGestureCoords,
2660 mPointerGesture.currentGestureIdToIndex,
2661 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2662 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002663 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2664 // Synthesize a hover move event after all pointers go up to indicate that
2665 // the pointer is hovering again even if the user is not currently touching
2666 // the touch pad. This ensures that a view will receive a fresh hover enter
2667 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002668 float x, y;
2669 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002670
2671 PointerProperties pointerProperties;
2672 pointerProperties.clear();
2673 pointerProperties.id = 0;
2674 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2675
2676 PointerCoords pointerCoords;
2677 pointerCoords.clear();
2678 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2679 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2680
2681 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002682 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2683 mSource, displayId, policyFlags,
2684 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2685 buttonState, MotionClassification::NONE,
2686 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2687 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2688 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002689 }
2690
2691 // Update state.
2692 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2693 if (!down) {
2694 mPointerGesture.lastGestureIdBits.clear();
2695 } else {
2696 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2697 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2698 uint32_t id = idBits.clearFirstMarkedBit();
2699 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2700 mPointerGesture.lastGestureProperties[index].copyFrom(
2701 mPointerGesture.currentGestureProperties[index]);
2702 mPointerGesture.lastGestureCoords[index].copyFrom(
2703 mPointerGesture.currentGestureCoords[index]);
2704 mPointerGesture.lastGestureIdToIndex[id] = index;
2705 }
2706 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002707 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002708}
2709
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002710std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2711 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002712 const MotionClassification classification =
2713 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2714 ? MotionClassification::TWO_FINGER_SWIPE
2715 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002716 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002717 // Cancel previously dispatches pointers.
2718 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2719 int32_t metaState = getContext()->getGlobalMetaState();
2720 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002721 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002722 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2723 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002724 mPointerGesture.lastGestureProperties,
2725 mPointerGesture.lastGestureCoords,
2726 mPointerGesture.lastGestureIdToIndex,
2727 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2728 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002729 }
2730
2731 // Reset the current pointer gesture.
2732 mPointerGesture.reset();
2733 mPointerVelocityControl.reset();
2734
2735 // Remove any current spots.
2736 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002737 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002738 mPointerController->clearSpots();
2739 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002740 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002741}
2742
2743bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2744 bool* outFinishPreviousGesture, bool isTimeout) {
2745 *outCancelPreviousGesture = false;
2746 *outFinishPreviousGesture = false;
2747
2748 // Handle TAP timeout.
2749 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002750 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002751
Michael Wright227c5542020-07-02 18:30:52 +01002752 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002753 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2754 // The tap/drag timeout has not yet expired.
2755 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2756 mConfig.pointerGestureTapDragInterval);
2757 } else {
2758 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002759 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002760 *outFinishPreviousGesture = true;
2761
2762 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002763 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002764 mPointerGesture.currentGestureIdBits.clear();
2765
2766 mPointerVelocityControl.reset();
2767 return true;
2768 }
2769 }
2770
2771 // We did not handle this timeout.
2772 return false;
2773 }
2774
2775 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2776 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2777
2778 // Update the velocity tracker.
2779 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002780 std::vector<float> positionsX;
2781 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002782 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002783 uint32_t id = idBits.clearFirstMarkedBit();
2784 const RawPointerData::Pointer& pointer =
2785 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002786 positionsX.push_back(pointer.x * mPointerXMovementScale);
2787 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 }
2789 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002790 {{AMOTION_EVENT_AXIS_X, positionsX},
2791 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002792 }
2793
2794 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2795 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002796 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2797 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2798 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002799 mPointerGesture.resetTap();
2800 }
2801
2802 // Pick a new active touch id if needed.
2803 // Choose an arbitrary pointer that just went down, if there is one.
2804 // Otherwise choose an arbitrary remaining pointer.
2805 // This guarantees we always have an active touch id when there is at least one pointer.
2806 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002807 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002808 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002809 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002810 mPointerGesture.firstTouchTime = when;
2811 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002812 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2813 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2814 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2815 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002816 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002817 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002818
2819 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002820 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002821 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002822 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2823 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2824 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002825 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826 *outFinishPreviousGesture = true;
2827 }
2828
2829 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002830 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002831 mPointerGesture.currentGestureIdBits.clear();
2832
2833 mPointerVelocityControl.reset();
2834 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2835 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2836 // The pointer follows the active touch point.
2837 // Emit DOWN, MOVE, UP events at the pointer location.
2838 //
2839 // Only the active touch matters; other fingers are ignored. This policy helps
2840 // to handle the case where the user places a second finger on the touch pad
2841 // to apply the necessary force to depress an integrated button below the surface.
2842 // We don't want the second finger to be delivered to applications.
2843 //
2844 // For this to work well, we need to make sure to track the pointer that is really
2845 // active. If the user first puts one finger down to click then adds another
2846 // finger to drag then the active pointer should switch to the finger that is
2847 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002848 ALOGD_IF(DEBUG_GESTURES,
2849 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2850 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002851 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002852 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002853 *outFinishPreviousGesture = true;
2854 mPointerGesture.activeGestureId = 0;
2855 }
2856
2857 // Switch pointers if needed.
2858 // Find the fastest pointer and follow it.
2859 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002860 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002861 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002862 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002863 ALOGD_IF(DEBUG_GESTURES,
2864 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2865 "bestSpeed=%0.3f",
2866 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 }
2868 }
2869
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002870 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002871 // When using spots, the click will occur at the position of the anchor
2872 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002873 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002874 } else {
2875 mPointerVelocityControl.reset();
2876 }
2877
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002878 float x, y;
2879 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002880
Michael Wright227c5542020-07-02 18:30:52 +01002881 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002882 mPointerGesture.currentGestureIdBits.clear();
2883 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2884 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2885 mPointerGesture.currentGestureProperties[0].clear();
2886 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2887 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2888 mPointerGesture.currentGestureCoords[0].clear();
2889 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2890 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2891 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2892 } else if (currentFingerCount == 0) {
2893 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002894 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 *outFinishPreviousGesture = true;
2896 }
2897
2898 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2899 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2900 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002901 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2902 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903 lastFingerCount == 1) {
2904 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002905 float x, y;
2906 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2908 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002909 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910
2911 mPointerGesture.tapUpTime = when;
2912 getContext()->requestTimeoutAtTime(when +
2913 mConfig.pointerGestureTapDragInterval);
2914
2915 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002916 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002917 mPointerGesture.currentGestureIdBits.clear();
2918 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2919 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2920 mPointerGesture.currentGestureProperties[0].clear();
2921 mPointerGesture.currentGestureProperties[0].id =
2922 mPointerGesture.activeGestureId;
2923 mPointerGesture.currentGestureProperties[0].toolType =
2924 AMOTION_EVENT_TOOL_TYPE_FINGER;
2925 mPointerGesture.currentGestureCoords[0].clear();
2926 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2927 mPointerGesture.tapX);
2928 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2929 mPointerGesture.tapY);
2930 mPointerGesture.currentGestureCoords[0]
2931 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2932
2933 tapped = true;
2934 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002935 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2936 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002937 }
2938 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002939 if (DEBUG_GESTURES) {
2940 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2941 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2942 (when - mPointerGesture.tapDownTime) * 0.000001f);
2943 } else {
2944 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2945 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002946 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002947 }
2948 }
2949
2950 mPointerVelocityControl.reset();
2951
2952 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002953 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002955 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002956 mPointerGesture.currentGestureIdBits.clear();
2957 }
2958 } else if (currentFingerCount == 1) {
2959 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2960 // The pointer follows the active touch point.
2961 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2962 // When in TAP_DRAG, emit MOVE events at the pointer location.
2963 ALOG_ASSERT(activeTouchId >= 0);
2964
Michael Wright227c5542020-07-02 18:30:52 +01002965 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2966 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002967 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002968 float x, y;
2969 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2971 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002972 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002974 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2975 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002976 }
2977 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002978 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2979 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002980 }
Michael Wright227c5542020-07-02 18:30:52 +01002981 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2982 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002983 }
2984
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002985 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002987 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 } else {
2989 mPointerVelocityControl.reset();
2990 }
2991
2992 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002993 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002994 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002995 down = true;
2996 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002997 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002998 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002999 *outFinishPreviousGesture = true;
3000 }
3001 mPointerGesture.activeGestureId = 0;
3002 down = false;
3003 }
3004
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003005 float x, y;
3006 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003007
3008 mPointerGesture.currentGestureIdBits.clear();
3009 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3010 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3011 mPointerGesture.currentGestureProperties[0].clear();
3012 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3013 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3014 mPointerGesture.currentGestureCoords[0].clear();
3015 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3016 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3017 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3018 down ? 1.0f : 0.0f);
3019
3020 if (lastFingerCount == 0 && currentFingerCount != 0) {
3021 mPointerGesture.resetTap();
3022 mPointerGesture.tapDownTime = when;
3023 mPointerGesture.tapX = x;
3024 mPointerGesture.tapY = y;
3025 }
3026 } else {
3027 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003028 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003029 }
3030
3031 mPointerController->setButtonState(mCurrentRawState.buttonState);
3032
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003033 if (DEBUG_GESTURES) {
3034 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3035 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3036 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3037 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3038 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3039 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3040 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3041 uint32_t id = idBits.clearFirstMarkedBit();
3042 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3043 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3044 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3045 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3046 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3047 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3048 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3049 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3050 }
3051 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3052 uint32_t id = idBits.clearFirstMarkedBit();
3053 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3054 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3055 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3056 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3057 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3058 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3059 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3060 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3061 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003062 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003063 return true;
3064}
3065
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003066bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3067 if (mPointerGesture.activeTouchId < 0) {
3068 mPointerGesture.resetQuietTime();
3069 return false;
3070 }
3071
3072 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3073 return true;
3074 }
3075
3076 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3077 bool isQuietTime = false;
3078 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3079 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3080 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3081 currentFingerCount < 2) {
3082 // Enter quiet time when exiting swipe or freeform state.
3083 // This is to prevent accidentally entering the hover state and flinging the
3084 // pointer when finishing a swipe and there is still one pointer left onscreen.
3085 isQuietTime = true;
3086 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3087 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3088 // Enter quiet time when releasing the button and there are still two or more
3089 // fingers down. This may indicate that one finger was used to press the button
3090 // but it has not gone up yet.
3091 isQuietTime = true;
3092 }
3093 if (isQuietTime) {
3094 mPointerGesture.quietTime = when;
3095 }
3096 return isQuietTime;
3097}
3098
3099std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3100 int32_t bestId = -1;
3101 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3102 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3103 uint32_t id = idBits.clearFirstMarkedBit();
3104 std::optional<float> vx =
3105 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3106 std::optional<float> vy =
3107 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3108 if (vx && vy) {
3109 float speed = hypotf(*vx, *vy);
3110 if (speed > bestSpeed) {
3111 bestId = id;
3112 bestSpeed = speed;
3113 }
3114 }
3115 }
3116 return std::make_pair(bestId, bestSpeed);
3117}
3118
3119void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3120 bool* finishPreviousGesture) {
3121 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3122 // to move before deciding what to do.
3123 //
3124 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3125 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3126 // just a press or long-press at the pointer location.
3127 //
3128 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3129 // pointer location.
3130 //
3131 // When the two fingers move enough or when additional fingers are added, we make a decision to
3132 // transition into SWIPE or FREEFORM mode accordingly.
3133 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3134 ALOG_ASSERT(activeTouchId >= 0);
3135
3136 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3137 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3138 bool settled =
3139 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3140 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3141 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3142 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3143 *finishPreviousGesture = true;
3144 } else if (!settled && currentFingerCount > lastFingerCount) {
3145 // Additional pointers have gone down but not yet settled.
3146 // Reset the gesture.
3147 ALOGD_IF(DEBUG_GESTURES,
3148 "Gestures: Resetting gesture since additional pointers went down for "
3149 "MULTITOUCH, settle time remaining %0.3fms",
3150 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3151 when) * 0.000001f);
3152 *cancelPreviousGesture = true;
3153 } else {
3154 // Continue previous gesture.
3155 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3156 }
3157
3158 if (*finishPreviousGesture || *cancelPreviousGesture) {
3159 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3160 mPointerGesture.activeGestureId = 0;
3161 mPointerGesture.referenceIdBits.clear();
3162 mPointerVelocityControl.reset();
3163
3164 // Use the centroid and pointer location as the reference points for the gesture.
3165 ALOGD_IF(DEBUG_GESTURES,
3166 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3167 "%0.3fms",
3168 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3169 when) * 0.000001f);
3170 mCurrentRawState.rawPointerData
3171 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3172 &mPointerGesture.referenceTouchY);
3173 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3174 &mPointerGesture.referenceGestureY);
3175 }
3176
3177 // Clear the reference deltas for fingers not yet included in the reference calculation.
3178 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3179 ~mPointerGesture.referenceIdBits.value);
3180 !idBits.isEmpty();) {
3181 uint32_t id = idBits.clearFirstMarkedBit();
3182 mPointerGesture.referenceDeltas[id].dx = 0;
3183 mPointerGesture.referenceDeltas[id].dy = 0;
3184 }
3185 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3186
3187 // Add delta for all fingers and calculate a common movement delta.
3188 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3189 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3190 mCurrentCookedState.fingerIdBits.value);
3191 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3192 bool first = (idBits == commonIdBits);
3193 uint32_t id = idBits.clearFirstMarkedBit();
3194 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3195 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3196 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3197 delta.dx += cpd.x - lpd.x;
3198 delta.dy += cpd.y - lpd.y;
3199
3200 if (first) {
3201 commonDeltaRawX = delta.dx;
3202 commonDeltaRawY = delta.dy;
3203 } else {
3204 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3205 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3206 }
3207 }
3208
3209 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3210 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3211 float dist[MAX_POINTER_ID + 1];
3212 int32_t distOverThreshold = 0;
3213 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3214 uint32_t id = idBits.clearFirstMarkedBit();
3215 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3216 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3217 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3218 distOverThreshold += 1;
3219 }
3220 }
3221
3222 // Only transition when at least two pointers have moved further than
3223 // the minimum distance threshold.
3224 if (distOverThreshold >= 2) {
3225 if (currentFingerCount > 2) {
3226 // There are more than two pointers, switch to FREEFORM.
3227 ALOGD_IF(DEBUG_GESTURES,
3228 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3229 currentFingerCount);
3230 *cancelPreviousGesture = true;
3231 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3232 } else {
3233 // There are exactly two pointers.
3234 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3235 uint32_t id1 = idBits.clearFirstMarkedBit();
3236 uint32_t id2 = idBits.firstMarkedBit();
3237 const RawPointerData::Pointer& p1 =
3238 mCurrentRawState.rawPointerData.pointerForId(id1);
3239 const RawPointerData::Pointer& p2 =
3240 mCurrentRawState.rawPointerData.pointerForId(id2);
3241 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3242 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3243 // There are two pointers but they are too far apart for a SWIPE,
3244 // switch to FREEFORM.
3245 ALOGD_IF(DEBUG_GESTURES,
3246 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3247 mutualDistance, mPointerGestureMaxSwipeWidth);
3248 *cancelPreviousGesture = true;
3249 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3250 } else {
3251 // There are two pointers. Wait for both pointers to start moving
3252 // before deciding whether this is a SWIPE or FREEFORM gesture.
3253 float dist1 = dist[id1];
3254 float dist2 = dist[id2];
3255 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3256 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3257 // Calculate the dot product of the displacement vectors.
3258 // When the vectors are oriented in approximately the same direction,
3259 // the angle betweeen them is near zero and the cosine of the angle
3260 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3261 // mag(v2).
3262 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3263 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3264 float dx1 = delta1.dx * mPointerXZoomScale;
3265 float dy1 = delta1.dy * mPointerYZoomScale;
3266 float dx2 = delta2.dx * mPointerXZoomScale;
3267 float dy2 = delta2.dy * mPointerYZoomScale;
3268 float dot = dx1 * dx2 + dy1 * dy2;
3269 float cosine = dot / (dist1 * dist2); // denominator always > 0
3270 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3271 // Pointers are moving in the same direction. Switch to SWIPE.
3272 ALOGD_IF(DEBUG_GESTURES,
3273 "Gestures: PRESS transitioned to SWIPE, "
3274 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3275 "cosine %0.3f >= %0.3f",
3276 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3277 mConfig.pointerGestureMultitouchMinDistance, cosine,
3278 mConfig.pointerGestureSwipeTransitionAngleCosine);
3279 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3280 } else {
3281 // Pointers are moving in different directions. Switch to FREEFORM.
3282 ALOGD_IF(DEBUG_GESTURES,
3283 "Gestures: PRESS transitioned to FREEFORM, "
3284 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3285 "cosine %0.3f < %0.3f",
3286 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3287 mConfig.pointerGestureMultitouchMinDistance, cosine,
3288 mConfig.pointerGestureSwipeTransitionAngleCosine);
3289 *cancelPreviousGesture = true;
3290 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3291 }
3292 }
3293 }
3294 }
3295 }
3296 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3297 // Switch from SWIPE to FREEFORM if additional pointers go down.
3298 // Cancel previous gesture.
3299 if (currentFingerCount > 2) {
3300 ALOGD_IF(DEBUG_GESTURES,
3301 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3302 currentFingerCount);
3303 *cancelPreviousGesture = true;
3304 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3305 }
3306 }
3307
3308 // Move the reference points based on the overall group motion of the fingers
3309 // except in PRESS mode while waiting for a transition to occur.
3310 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3311 (commonDeltaRawX || commonDeltaRawY)) {
3312 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3313 uint32_t id = idBits.clearFirstMarkedBit();
3314 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3315 delta.dx = 0;
3316 delta.dy = 0;
3317 }
3318
3319 mPointerGesture.referenceTouchX += commonDeltaRawX;
3320 mPointerGesture.referenceTouchY += commonDeltaRawY;
3321
3322 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3323 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3324
3325 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3326 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3327
3328 mPointerGesture.referenceGestureX += commonDeltaX;
3329 mPointerGesture.referenceGestureY += commonDeltaY;
3330 }
3331
3332 // Report gestures.
3333 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3334 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3335 // PRESS or SWIPE mode.
3336 ALOGD_IF(DEBUG_GESTURES,
3337 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3338 "currentTouchPointerCount=%d",
3339 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3340 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3341
3342 mPointerGesture.currentGestureIdBits.clear();
3343 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3344 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3345 mPointerGesture.currentGestureProperties[0].clear();
3346 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3347 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3348 mPointerGesture.currentGestureCoords[0].clear();
3349 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3350 mPointerGesture.referenceGestureX);
3351 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3352 mPointerGesture.referenceGestureY);
3353 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3354 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3355 float xOffset = static_cast<float>(commonDeltaRawX) /
3356 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3357 float yOffset = static_cast<float>(commonDeltaRawY) /
3358 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3359 mPointerGesture.currentGestureCoords[0]
3360 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3361 mPointerGesture.currentGestureCoords[0]
3362 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3363 }
3364 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3365 // FREEFORM mode.
3366 ALOGD_IF(DEBUG_GESTURES,
3367 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3368 "currentTouchPointerCount=%d",
3369 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3370 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3371
3372 mPointerGesture.currentGestureIdBits.clear();
3373
3374 BitSet32 mappedTouchIdBits;
3375 BitSet32 usedGestureIdBits;
3376 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3377 // Initially, assign the active gesture id to the active touch point
3378 // if there is one. No other touch id bits are mapped yet.
3379 if (!*cancelPreviousGesture) {
3380 mappedTouchIdBits.markBit(activeTouchId);
3381 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3382 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3383 mPointerGesture.activeGestureId;
3384 } else {
3385 mPointerGesture.activeGestureId = -1;
3386 }
3387 } else {
3388 // Otherwise, assume we mapped all touches from the previous frame.
3389 // Reuse all mappings that are still applicable.
3390 mappedTouchIdBits.value =
3391 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3392 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3393
3394 // Check whether we need to choose a new active gesture id because the
3395 // current went went up.
3396 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3397 ~mCurrentCookedState.fingerIdBits.value);
3398 !upTouchIdBits.isEmpty();) {
3399 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3400 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3401 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3402 mPointerGesture.activeGestureId = -1;
3403 break;
3404 }
3405 }
3406 }
3407
3408 ALOGD_IF(DEBUG_GESTURES,
3409 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3410 "activeGestureId=%d",
3411 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3412
3413 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3414 for (uint32_t i = 0; i < currentFingerCount; i++) {
3415 uint32_t touchId = idBits.clearFirstMarkedBit();
3416 uint32_t gestureId;
3417 if (!mappedTouchIdBits.hasBit(touchId)) {
3418 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3419 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3420 ALOGD_IF(DEBUG_GESTURES,
3421 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3422 gestureId);
3423 } else {
3424 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3425 ALOGD_IF(DEBUG_GESTURES,
3426 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3427 touchId, gestureId);
3428 }
3429 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3430 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3431
3432 const RawPointerData::Pointer& pointer =
3433 mCurrentRawState.rawPointerData.pointerForId(touchId);
3434 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3435 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3436 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3437
3438 mPointerGesture.currentGestureProperties[i].clear();
3439 mPointerGesture.currentGestureProperties[i].id = gestureId;
3440 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3441 mPointerGesture.currentGestureCoords[i].clear();
3442 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3443 mPointerGesture.referenceGestureX +
3444 deltaX);
3445 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3446 mPointerGesture.referenceGestureY +
3447 deltaY);
3448 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3449 }
3450
3451 if (mPointerGesture.activeGestureId < 0) {
3452 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3453 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3454 mPointerGesture.activeGestureId);
3455 }
3456 }
3457}
3458
Harry Cutts714d1ad2022-08-24 16:36:43 +00003459void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3460 const RawPointerData::Pointer& currentPointer =
3461 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3462 const RawPointerData::Pointer& lastPointer =
3463 mLastRawState.rawPointerData.pointerForId(pointerId);
3464 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3465 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3466
3467 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3468 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3469
3470 mPointerController->move(deltaX, deltaY);
3471}
3472
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003473std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3474 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003475 mPointerSimple.currentCoords.clear();
3476 mPointerSimple.currentProperties.clear();
3477
3478 bool down, hovering;
3479 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3480 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3481 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003482 mPointerController
3483 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3484 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003485
3486 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3487 down = !hovering;
3488
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003489 float x, y;
3490 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003491 mPointerSimple.currentCoords.copyFrom(
3492 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3493 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3494 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3495 mPointerSimple.currentProperties.id = 0;
3496 mPointerSimple.currentProperties.toolType =
3497 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3498 } else {
3499 down = false;
3500 hovering = false;
3501 }
3502
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003503 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003504}
3505
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003506std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3507 uint32_t policyFlags) {
3508 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509}
3510
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003511std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3512 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003513 mPointerSimple.currentCoords.clear();
3514 mPointerSimple.currentProperties.clear();
3515
3516 bool down, hovering;
3517 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3518 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003519 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003520 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003521 } else {
3522 mPointerVelocityControl.reset();
3523 }
3524
3525 down = isPointerDown(mCurrentRawState.buttonState);
3526 hovering = !down;
3527
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003528 float x, y;
3529 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003530 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003531 mPointerSimple.currentCoords.copyFrom(
3532 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3533 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3534 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3535 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3536 hovering ? 0.0f : 1.0f);
3537 mPointerSimple.currentProperties.id = 0;
3538 mPointerSimple.currentProperties.toolType =
3539 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3540 } else {
3541 mPointerVelocityControl.reset();
3542
3543 down = false;
3544 hovering = false;
3545 }
3546
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003547 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003548}
3549
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003550std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3551 uint32_t policyFlags) {
3552 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003553
3554 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003555
3556 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003557}
3558
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003559std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3560 uint32_t policyFlags, bool down,
3561 bool hovering) {
3562 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003564
3565 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003566 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567 mPointerController->clearSpots();
3568 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003569 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003571 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572 }
Garfield Tan9514d782020-11-10 16:37:23 -08003573 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003574
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003575 float xCursorPosition, yCursorPosition;
3576 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003577
3578 if (mPointerSimple.down && !down) {
3579 mPointerSimple.down = false;
3580
3581 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003582 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3583 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3584 0, metaState, mLastRawState.buttonState,
3585 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3586 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3587 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3588 yCursorPosition, mPointerSimple.downTime,
3589 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590 }
3591
3592 if (mPointerSimple.hovering && !hovering) {
3593 mPointerSimple.hovering = false;
3594
3595 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003596 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3597 mSource, displayId, policyFlags,
3598 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3599 mLastRawState.buttonState, MotionClassification::NONE,
3600 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3601 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3602 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3603 yCursorPosition, mPointerSimple.downTime,
3604 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003605 }
3606
3607 if (down) {
3608 if (!mPointerSimple.down) {
3609 mPointerSimple.down = true;
3610 mPointerSimple.downTime = when;
3611
3612 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003613 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3614 mSource, displayId, policyFlags,
3615 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3616 mCurrentRawState.buttonState, MotionClassification::NONE,
3617 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3618 &mPointerSimple.currentProperties,
3619 &mPointerSimple.currentCoords, mOrientedXPrecision,
3620 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3621 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003622 }
3623
3624 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003625 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3626 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3627 0, 0, metaState, mCurrentRawState.buttonState,
3628 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3629 &mPointerSimple.currentProperties,
3630 &mPointerSimple.currentCoords, mOrientedXPrecision,
3631 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3632 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003633 }
3634
3635 if (hovering) {
3636 if (!mPointerSimple.hovering) {
3637 mPointerSimple.hovering = true;
3638
3639 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003640 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3641 mSource, displayId, policyFlags,
3642 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3643 mCurrentRawState.buttonState, MotionClassification::NONE,
3644 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3645 &mPointerSimple.currentProperties,
3646 &mPointerSimple.currentCoords, mOrientedXPrecision,
3647 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3648 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003649 }
3650
3651 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003652 out.push_back(
3653 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3654 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3655 metaState, mCurrentRawState.buttonState,
3656 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3657 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3658 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3659 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003660 }
3661
3662 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3663 float vscroll = mCurrentRawState.rawVScroll;
3664 float hscroll = mCurrentRawState.rawHScroll;
3665 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3666 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3667
3668 // Send scroll.
3669 PointerCoords pointerCoords;
3670 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3671 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3672 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3673
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003674 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3675 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3676 0, 0, metaState, mCurrentRawState.buttonState,
3677 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3678 &mPointerSimple.currentProperties, &pointerCoords,
3679 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3680 yCursorPosition, mPointerSimple.downTime,
3681 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003682 }
3683
3684 // Save state.
3685 if (down || hovering) {
3686 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3687 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3688 } else {
3689 mPointerSimple.reset();
3690 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003691 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003692}
3693
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003694std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3695 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696 mPointerSimple.currentCoords.clear();
3697 mPointerSimple.currentProperties.clear();
3698
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003699 return dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003700}
3701
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003702NotifyMotionArgs TouchInputMapper::dispatchMotion(
3703 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3704 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003705 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3706 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003707 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003708 PointerCoords pointerCoords[MAX_POINTERS];
3709 PointerProperties pointerProperties[MAX_POINTERS];
3710 uint32_t pointerCount = 0;
3711 while (!idBits.isEmpty()) {
3712 uint32_t id = idBits.clearFirstMarkedBit();
3713 uint32_t index = idToIndex[id];
3714 pointerProperties[pointerCount].copyFrom(properties[index]);
3715 pointerCoords[pointerCount].copyFrom(coords[index]);
3716
3717 if (changedId >= 0 && id == uint32_t(changedId)) {
3718 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3719 }
3720
3721 pointerCount += 1;
3722 }
3723
3724 ALOG_ASSERT(pointerCount != 0);
3725
3726 if (changedId >= 0 && pointerCount == 1) {
3727 // Replace initial down and final up action.
3728 // We can compare the action without masking off the changed pointer index
3729 // because we know the index is 0.
3730 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3731 action = AMOTION_EVENT_ACTION_DOWN;
3732 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003733 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3734 action = AMOTION_EVENT_ACTION_CANCEL;
3735 } else {
3736 action = AMOTION_EVENT_ACTION_UP;
3737 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003738 } else {
3739 // Can't happen.
3740 ALOG_ASSERT(false);
3741 }
3742 }
3743 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3744 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003745 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003746 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003747 }
3748 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3749 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003750 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003751 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003752 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003753 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3754 policyFlags, action, actionButton, flags, metaState, buttonState,
3755 classification, edgeFlags, pointerCount, pointerProperties,
3756 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3757 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003758}
3759
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003760std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3761 std::list<NotifyArgs> out;
3762 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3763 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3764 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003765}
3766
Prabir Pradhan1728b212021-10-19 16:00:03 -07003767// Transform input device coordinates to display panel coordinates.
3768void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003769 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3770 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3771
arthurhunga36b28e2020-12-29 20:28:15 +08003772 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3773 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3774
Prabir Pradhan1728b212021-10-19 16:00:03 -07003775 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003776 // 0 - no swap and reverse.
3777 // 90 - swap x/y and reverse y.
3778 // 180 - reverse x, y.
3779 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003780 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003781 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003782 x = xScaled;
3783 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003784 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003785 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003786 y = xScaledMax;
3787 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003788 break;
3789 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003790 x = xScaledMax;
3791 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003792 break;
3793 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003794 y = xScaled;
3795 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003796 break;
3797 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003798 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003799 }
3800}
3801
Prabir Pradhan1728b212021-10-19 16:00:03 -07003802bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003803 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3804 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3805
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003806 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003807 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003808 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003809 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003810}
3811
3812const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3813 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003814 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3815 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3816 "left=%d, top=%d, right=%d, bottom=%d",
3817 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3818 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003819
3820 if (virtualKey.isHit(x, y)) {
3821 return &virtualKey;
3822 }
3823 }
3824
3825 return nullptr;
3826}
3827
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003828void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3829 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3830 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003831
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003832 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003833
3834 if (currentPointerCount == 0) {
3835 // No pointers to assign.
3836 return;
3837 }
3838
3839 if (lastPointerCount == 0) {
3840 // All pointers are new.
3841 for (uint32_t i = 0; i < currentPointerCount; i++) {
3842 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003843 current.rawPointerData.pointers[i].id = id;
3844 current.rawPointerData.idToIndex[id] = i;
3845 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003846 }
3847 return;
3848 }
3849
3850 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003851 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003852 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003853 uint32_t id = last.rawPointerData.pointers[0].id;
3854 current.rawPointerData.pointers[0].id = id;
3855 current.rawPointerData.idToIndex[id] = 0;
3856 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003857 return;
3858 }
3859
3860 // General case.
3861 // We build a heap of squared euclidean distances between current and last pointers
3862 // associated with the current and last pointer indices. Then, we find the best
3863 // match (by distance) for each current pointer.
3864 // The pointers must have the same tool type but it is possible for them to
3865 // transition from hovering to touching or vice-versa while retaining the same id.
3866 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3867
3868 uint32_t heapSize = 0;
3869 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3870 currentPointerIndex++) {
3871 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3872 lastPointerIndex++) {
3873 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003874 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003875 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003876 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003877 if (currentPointer.toolType == lastPointer.toolType) {
3878 int64_t deltaX = currentPointer.x - lastPointer.x;
3879 int64_t deltaY = currentPointer.y - lastPointer.y;
3880
3881 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3882
3883 // Insert new element into the heap (sift up).
3884 heap[heapSize].currentPointerIndex = currentPointerIndex;
3885 heap[heapSize].lastPointerIndex = lastPointerIndex;
3886 heap[heapSize].distance = distance;
3887 heapSize += 1;
3888 }
3889 }
3890 }
3891
3892 // Heapify
3893 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3894 startIndex -= 1;
3895 for (uint32_t parentIndex = startIndex;;) {
3896 uint32_t childIndex = parentIndex * 2 + 1;
3897 if (childIndex >= heapSize) {
3898 break;
3899 }
3900
3901 if (childIndex + 1 < heapSize &&
3902 heap[childIndex + 1].distance < heap[childIndex].distance) {
3903 childIndex += 1;
3904 }
3905
3906 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3907 break;
3908 }
3909
3910 swap(heap[parentIndex], heap[childIndex]);
3911 parentIndex = childIndex;
3912 }
3913 }
3914
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003915 if (DEBUG_POINTER_ASSIGNMENT) {
3916 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3917 for (size_t i = 0; i < heapSize; i++) {
3918 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3919 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3920 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003921 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003922
3923 // Pull matches out by increasing order of distance.
3924 // To avoid reassigning pointers that have already been matched, the loop keeps track
3925 // of which last and current pointers have been matched using the matchedXXXBits variables.
3926 // It also tracks the used pointer id bits.
3927 BitSet32 matchedLastBits(0);
3928 BitSet32 matchedCurrentBits(0);
3929 BitSet32 usedIdBits(0);
3930 bool first = true;
3931 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3932 while (heapSize > 0) {
3933 if (first) {
3934 // The first time through the loop, we just consume the root element of
3935 // the heap (the one with smallest distance).
3936 first = false;
3937 } else {
3938 // Previous iterations consumed the root element of the heap.
3939 // Pop root element off of the heap (sift down).
3940 heap[0] = heap[heapSize];
3941 for (uint32_t parentIndex = 0;;) {
3942 uint32_t childIndex = parentIndex * 2 + 1;
3943 if (childIndex >= heapSize) {
3944 break;
3945 }
3946
3947 if (childIndex + 1 < heapSize &&
3948 heap[childIndex + 1].distance < heap[childIndex].distance) {
3949 childIndex += 1;
3950 }
3951
3952 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3953 break;
3954 }
3955
3956 swap(heap[parentIndex], heap[childIndex]);
3957 parentIndex = childIndex;
3958 }
3959
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003960 if (DEBUG_POINTER_ASSIGNMENT) {
3961 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3962 for (size_t j = 0; j < heapSize; j++) {
3963 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3964 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3965 heap[j].distance);
3966 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003967 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003968 }
3969
3970 heapSize -= 1;
3971
3972 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3973 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3974
3975 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3976 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3977
3978 matchedCurrentBits.markBit(currentPointerIndex);
3979 matchedLastBits.markBit(lastPointerIndex);
3980
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003981 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3982 current.rawPointerData.pointers[currentPointerIndex].id = id;
3983 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3984 current.rawPointerData.markIdBit(id,
3985 current.rawPointerData.isHovering(
3986 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003987 usedIdBits.markBit(id);
3988
Harry Cutts45483602022-08-24 14:36:48 +00003989 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3990 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3991 ", distance=%" PRIu64,
3992 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003993 break;
3994 }
3995 }
3996
3997 // Assign fresh ids to pointers that were not matched in the process.
3998 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3999 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4000 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4001
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004002 current.rawPointerData.pointers[currentPointerIndex].id = id;
4003 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4004 current.rawPointerData.markIdBit(id,
4005 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004006
Harry Cutts45483602022-08-24 14:36:48 +00004007 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4008 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4009 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004010 }
4011}
4012
4013int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4014 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4015 return AKEY_STATE_VIRTUAL;
4016 }
4017
4018 for (const VirtualKey& virtualKey : mVirtualKeys) {
4019 if (virtualKey.keyCode == keyCode) {
4020 return AKEY_STATE_UP;
4021 }
4022 }
4023
4024 return AKEY_STATE_UNKNOWN;
4025}
4026
4027int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4028 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4029 return AKEY_STATE_VIRTUAL;
4030 }
4031
4032 for (const VirtualKey& virtualKey : mVirtualKeys) {
4033 if (virtualKey.scanCode == scanCode) {
4034 return AKEY_STATE_UP;
4035 }
4036 }
4037
4038 return AKEY_STATE_UNKNOWN;
4039}
4040
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004041bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4042 const std::vector<int32_t>& keyCodes,
4043 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004044 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004045 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004046 if (virtualKey.keyCode == keyCodes[i]) {
4047 outFlags[i] = 1;
4048 }
4049 }
4050 }
4051
4052 return true;
4053}
4054
4055std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4056 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004057 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004058 return std::make_optional(mPointerController->getDisplayId());
4059 } else {
4060 return std::make_optional(mViewport.displayId);
4061 }
4062 }
4063 return std::nullopt;
4064}
4065
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004066} // namespace android