blob: d14b0f08f1847aaca6a1001e97a7912f6d06e292 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
24
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070025#include "CursorButtonAccumulator.h"
26#include "CursorScrollAccumulator.h"
27#include "TouchButtonAccumulator.h"
28#include "TouchCursorInputMapperCommon.h"
29
30namespace android {
31
32// --- Constants ---
33
34// Maximum amount of latency to add to touch events while waiting for data from an
35// external stylus.
36static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
37
38// Maximum amount of time to wait on touch data before pushing out new pressure data.
39static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
40
41// Artificial latency on synthetic events created from stylus data without corresponding touch
42// data.
43static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
44
HQ Liue6983c72022-04-19 22:14:56 +000045// Minimum width between two pointers to determine a gesture as freeform gesture in mm
46static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070047// --- Static Definitions ---
48
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000049static const DisplayViewport kUninitializedViewport;
50
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070051template <typename T>
52inline static void swap(T& a, T& b) {
53 T temp = a;
54 a = b;
55 b = temp;
56}
57
58static float calculateCommonVector(float a, float b) {
59 if (a > 0 && b > 0) {
60 return a < b ? a : b;
61 } else if (a < 0 && b < 0) {
62 return a > b ? a : b;
63 } else {
64 return 0;
65 }
66}
67
68inline static float distance(float x1, float y1, float x2, float y2) {
69 return hypotf(x1 - x2, y1 - y2);
70}
71
72inline static int32_t signExtendNybble(int32_t value) {
73 return value >= 8 ? value - 16 : value;
74}
75
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070076// --- RawPointerData ---
77
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070078void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
79 float x = 0, y = 0;
80 uint32_t count = touchingIdBits.count();
81 if (count) {
82 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
83 uint32_t id = idBits.clearFirstMarkedBit();
84 const Pointer& pointer = pointerForId(id);
85 x += pointer.x;
86 y += pointer.y;
87 }
88 x /= count;
89 y /= count;
90 }
91 *outX = x;
92 *outY = y;
93}
94
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070095// --- TouchInputMapper ---
96
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -080097TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
98 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +000099 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700100 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100101 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700102 mDisplayWidth(-1),
103 mDisplayHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700104 mPhysicalWidth(-1),
105 mPhysicalHeight(-1),
106 mPhysicalLeft(0),
107 mPhysicalTop(0),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700108 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109
110TouchInputMapper::~TouchInputMapper() {}
111
Philip Junker4af3b3d2021-12-14 10:36:55 +0100112uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700113 return mSource;
114}
115
116void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
117 InputMapper::populateDeviceInfo(info);
118
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000119 if (mDeviceMode == DeviceMode::DISABLED) {
120 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700121 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000122
123 info->addMotionRange(mOrientedRanges.x);
124 info->addMotionRange(mOrientedRanges.y);
125 info->addMotionRange(mOrientedRanges.pressure);
126
127 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
128 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
129 //
130 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
131 // motion, i.e. the hardware dimensions, as the finger could move completely across the
132 // touchpad in one sample cycle.
133 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
134 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
135 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
136 x.resolution);
137 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
138 y.resolution);
139 }
140
141 if (mOrientedRanges.size) {
142 info->addMotionRange(*mOrientedRanges.size);
143 }
144
145 if (mOrientedRanges.touchMajor) {
146 info->addMotionRange(*mOrientedRanges.touchMajor);
147 info->addMotionRange(*mOrientedRanges.touchMinor);
148 }
149
150 if (mOrientedRanges.toolMajor) {
151 info->addMotionRange(*mOrientedRanges.toolMajor);
152 info->addMotionRange(*mOrientedRanges.toolMinor);
153 }
154
155 if (mOrientedRanges.orientation) {
156 info->addMotionRange(*mOrientedRanges.orientation);
157 }
158
159 if (mOrientedRanges.distance) {
160 info->addMotionRange(*mOrientedRanges.distance);
161 }
162
163 if (mOrientedRanges.tilt) {
164 info->addMotionRange(*mOrientedRanges.tilt);
165 }
166
167 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
168 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
169 }
170 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
171 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
172 }
173 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
174 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
175 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
176 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
177 x.resolution);
178 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
179 y.resolution);
180 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
181 x.resolution);
182 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
183 y.resolution);
184 }
185 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000186 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700187}
188
189void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700190 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800191 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 dumpParameters(dump);
193 dumpVirtualKeys(dump);
194 dumpRawPointerAxes(dump);
195 dumpCalibration(dump);
196 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700197 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700198
199 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700200 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
201 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
202 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
203 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
204 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
205 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
206 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
207 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
208 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
209 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
210 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
211 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
212 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
213 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
214
215 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
216 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
217 mLastRawState.rawPointerData.pointerCount);
218 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
219 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
220 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
221 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
222 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
223 "toolType=%d, isHovering=%s\n",
224 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
225 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
226 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
227 pointer.distance, pointer.toolType, toString(pointer.isHovering));
228 }
229
230 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
231 mLastCookedState.buttonState);
232 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
233 mLastCookedState.cookedPointerData.pointerCount);
234 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
235 const PointerProperties& pointerProperties =
236 mLastCookedState.cookedPointerData.pointerProperties[i];
237 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000238 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
239 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
240 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700241 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
242 "toolType=%d, isHovering=%s\n",
243 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000244 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
245 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700246 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
247 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
248 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
249 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
250 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
251 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
252 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
253 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
254 pointerProperties.toolType,
255 toString(mLastCookedState.cookedPointerData.isHovering(i)));
256 }
257
258 dump += INDENT3 "Stylus Fusion:\n";
259 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
260 toString(mExternalStylusConnected));
261 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
262 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
263 mExternalStylusFusionTimeout);
264 dump += INDENT3 "External Stylus State:\n";
265 dumpStylusState(dump, mExternalStylusState);
266
Michael Wright227c5542020-07-02 18:30:52 +0100267 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700268 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
269 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
270 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
271 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
272 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
273 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
274 }
275}
276
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700277std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
278 const InputReaderConfiguration* config,
279 uint32_t changes) {
280 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700281
282 mConfig = *config;
283
284 if (!changes) { // first time only
285 // Configure basic parameters.
286 configureParameters();
287
288 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800289 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000290 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700291
292 // Configure absolute axis information.
293 configureRawPointerAxes();
294
295 // Prepare input device calibration.
296 parseCalibration();
297 resolveCalibration();
298 }
299
300 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
301 // Update location calibration to reflect current settings
302 updateAffineTransformation();
303 }
304
305 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
306 // Update pointer speed.
307 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
308 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
309 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
310 }
311
312 bool resetNeeded = false;
313 if (!changes ||
314 (changes &
315 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800316 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700317 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
318 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
319 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700320 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700321 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700322 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700323 }
324
325 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700326 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000327
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700328 // Send reset, unless this is the first time the device has been configured,
329 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000330 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700331 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700332 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333}
334
335void TouchInputMapper::resolveExternalStylusPresence() {
336 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800337 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700338 mExternalStylusConnected = !devices.empty();
339
340 if (!mExternalStylusConnected) {
341 resetExternalStylus();
342 }
343}
344
345void TouchInputMapper::configureParameters() {
346 // Use the pointer presentation mode for devices that do not support distinct
347 // multitouch. The spot-based presentation relies on being able to accurately
348 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800349 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100350 ? Parameters::GestureMode::SINGLE_TOUCH
351 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700352
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700353 std::string gestureModeString;
354 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800355 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700356 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100357 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700358 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100359 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700360 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700361 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700362 }
363 }
364
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800365 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700366 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100367 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800368 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700369 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100370 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700371 } else {
372 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100373 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374 }
375
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800376 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700377
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700378 std::string deviceTypeString;
379 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800380 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700381 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100382 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700383 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100384 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700385 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100386 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700387 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700388 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 }
390 }
391
Michael Wright227c5542020-07-02 18:30:52 +0100392 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700393 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800394 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700395
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700396 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700397 std::string orientationString;
398 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700399 orientationString)) {
400 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
401 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
402 } else if (orientationString == "ORIENTATION_90") {
403 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
404 } else if (orientationString == "ORIENTATION_180") {
405 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
406 } else if (orientationString == "ORIENTATION_270") {
407 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
408 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700409 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700410 }
411 }
412
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700413 mParameters.hasAssociatedDisplay = false;
414 mParameters.associatedDisplayIsExternal = false;
415 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100416 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
417 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700418 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100419 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800420 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700421 std::string uniqueDisplayId;
422 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800423 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700424 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
425 }
426 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800427 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 mParameters.hasAssociatedDisplay = true;
429 }
430
431 // Initial downs on external touch devices should wake the device.
432 // Normally we don't do this for internal touch screens to prevent them from waking
433 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800434 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700435 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000436
437 mParameters.supportsUsi = false;
438 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
439 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700440
441 mParameters.enableForInactiveViewport = false;
442 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
443 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444}
445
446void TouchInputMapper::dumpParameters(std::string& dump) {
447 dump += INDENT3 "Parameters:\n";
448
Dominik Laskowski75788452021-02-09 18:51:25 -0800449 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450
Dominik Laskowski75788452021-02-09 18:51:25 -0800451 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452
453 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
454 "displayId='%s'\n",
455 toString(mParameters.hasAssociatedDisplay),
456 toString(mParameters.associatedDisplayIsExternal),
457 mParameters.uniqueDisplayId.c_str());
458 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800459 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000460 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700461 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
462 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463}
464
465void TouchInputMapper::configureRawPointerAxes() {
466 mRawPointerAxes.clear();
467}
468
469void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
470 dump += INDENT3 "Raw Touch Axes:\n";
471 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
472 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
473 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
474 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
475 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
476 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
477 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
478 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
479 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
480 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
481 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
482 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
483 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
484}
485
486bool TouchInputMapper::hasExternalStylus() const {
487 return mExternalStylusConnected;
488}
489
490/**
491 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000492 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800493 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000494 * 3. Get the matching viewport by either unique id in idc file or by the display type
495 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800496 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700497 */
498std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800499 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000500 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800501 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502 }
503
Christine Franks2a2293c2022-01-18 11:51:16 -0800504 const std::optional<std::string> associatedDisplayUniqueId =
505 getDeviceContext().getAssociatedDisplayUniqueId();
506 if (associatedDisplayUniqueId) {
507 return getDeviceContext().getAssociatedViewport();
508 }
509
Michael Wright227c5542020-07-02 18:30:52 +0100510 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800511 std::optional<DisplayViewport> viewport =
512 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
513 if (viewport) {
514 return viewport;
515 } else {
516 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
517 mConfig.defaultPointerDisplayId);
518 }
519 }
520
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700521 // Check if uniqueDisplayId is specified in idc file.
522 if (!mParameters.uniqueDisplayId.empty()) {
523 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
524 }
525
526 ViewportType viewportTypeToUse;
527 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100528 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700529 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100530 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700531 }
532
533 std::optional<DisplayViewport> viewport =
534 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100535 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700536 ALOGW("Input device %s should be associated with external display, "
537 "fallback to internal one for the external viewport is not found.",
538 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100539 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700540 }
541
542 return viewport;
543 }
544
545 // No associated display, return a non-display viewport.
546 DisplayViewport newViewport;
547 // Raw width and height in the natural orientation.
548 int32_t rawWidth = mRawPointerAxes.getRawWidth();
549 int32_t rawHeight = mRawPointerAxes.getRawHeight();
550 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
551 return std::make_optional(newViewport);
552}
553
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800554int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
555 if (resolution < 0) {
556 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
557 getDeviceName().c_str());
558 return 0;
559 }
560 return resolution;
561}
562
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800563void TouchInputMapper::initializeSizeRanges() {
564 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
565 mSizeScale = 0.0f;
566 return;
567 }
568
569 // Size of diagonal axis.
570 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
571
572 // Size factors.
573 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
574 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
575 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
576 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
577 } else {
578 mSizeScale = 0.0f;
579 }
580
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700581 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
582 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
583 .source = mSource,
584 .min = 0,
585 .max = diagonalSize,
586 .flat = 0,
587 .fuzz = 0,
588 .resolution = 0,
589 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800590
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800591 if (mRawPointerAxes.touchMajor.valid) {
592 mRawPointerAxes.touchMajor.resolution =
593 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700594 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800595 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800596
597 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700598 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800599 if (mRawPointerAxes.touchMinor.valid) {
600 mRawPointerAxes.touchMinor.resolution =
601 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700602 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800603 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800604
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700605 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
606 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
607 .source = mSource,
608 .min = 0,
609 .max = diagonalSize,
610 .flat = 0,
611 .fuzz = 0,
612 .resolution = 0,
613 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800614 if (mRawPointerAxes.toolMajor.valid) {
615 mRawPointerAxes.toolMajor.resolution =
616 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700617 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800618 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800619
620 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700621 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800622 if (mRawPointerAxes.toolMinor.valid) {
623 mRawPointerAxes.toolMinor.resolution =
624 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700625 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800626 }
627
628 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700629 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
630 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
631 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
632 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800633 } else {
634 // Support for other calibrations can be added here.
635 ALOGW("%s calibration is not supported for size ranges at the moment. "
636 "Using raw resolution instead",
637 ftl::enum_string(mCalibration.sizeCalibration).c_str());
638 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800639
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700640 mOrientedRanges.size = InputDeviceInfo::MotionRange{
641 .axis = AMOTION_EVENT_AXIS_SIZE,
642 .source = mSource,
643 .min = 0,
644 .max = 1.0,
645 .flat = 0,
646 .fuzz = 0,
647 .resolution = 0,
648 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800649}
650
651void TouchInputMapper::initializeOrientedRanges() {
652 // Configure X and Y factors.
653 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
654 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
655 mXPrecision = 1.0f / mXScale;
656 mYPrecision = 1.0f / mYScale;
657
658 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
659 mOrientedRanges.x.source = mSource;
660 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
661 mOrientedRanges.y.source = mSource;
662
663 // Scale factor for terms that are not oriented in a particular axis.
664 // If the pixels are square then xScale == yScale otherwise we fake it
665 // by choosing an average.
666 mGeometricScale = avg(mXScale, mYScale);
667
668 initializeSizeRanges();
669
670 // Pressure factors.
671 mPressureScale = 0;
672 float pressureMax = 1.0;
673 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
674 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700675 if (mCalibration.pressureScale) {
676 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800677 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
678 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
679 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
680 }
681 }
682
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700683 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
684 .axis = AMOTION_EVENT_AXIS_PRESSURE,
685 .source = mSource,
686 .min = 0,
687 .max = pressureMax,
688 .flat = 0,
689 .fuzz = 0,
690 .resolution = 0,
691 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800692
693 // Tilt
694 mTiltXCenter = 0;
695 mTiltXScale = 0;
696 mTiltYCenter = 0;
697 mTiltYScale = 0;
698 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
699 if (mHaveTilt) {
700 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
701 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
702 mTiltXScale = M_PI / 180;
703 mTiltYScale = M_PI / 180;
704
705 if (mRawPointerAxes.tiltX.resolution) {
706 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
707 }
708 if (mRawPointerAxes.tiltY.resolution) {
709 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
710 }
711
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700712 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
713 .axis = AMOTION_EVENT_AXIS_TILT,
714 .source = mSource,
715 .min = 0,
716 .max = M_PI_2,
717 .flat = 0,
718 .fuzz = 0,
719 .resolution = 0,
720 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800721 }
722
723 // Orientation
724 mOrientationScale = 0;
725 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700726 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
727 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
728 .source = mSource,
729 .min = -M_PI,
730 .max = M_PI,
731 .flat = 0,
732 .fuzz = 0,
733 .resolution = 0,
734 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800735
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800736 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
737 if (mCalibration.orientationCalibration ==
738 Calibration::OrientationCalibration::INTERPOLATED) {
739 if (mRawPointerAxes.orientation.valid) {
740 if (mRawPointerAxes.orientation.maxValue > 0) {
741 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
742 } else if (mRawPointerAxes.orientation.minValue < 0) {
743 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
744 } else {
745 mOrientationScale = 0;
746 }
747 }
748 }
749
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700750 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
751 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
752 .source = mSource,
753 .min = -M_PI_2,
754 .max = M_PI_2,
755 .flat = 0,
756 .fuzz = 0,
757 .resolution = 0,
758 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800759 }
760
761 // Distance
762 mDistanceScale = 0;
763 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
764 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700765 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800766 }
767
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700768 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800769
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700770 .axis = AMOTION_EVENT_AXIS_DISTANCE,
771 .source = mSource,
772 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
773 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
774 .flat = 0,
775 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
776 .resolution = 0,
777 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800778 }
779
780 // Compute oriented precision, scales and ranges.
781 // Note that the maximum value reported is an inclusive maximum value so it is one
782 // unit less than the total width or height of the display.
783 switch (mInputDeviceOrientation) {
784 case DISPLAY_ORIENTATION_90:
785 case DISPLAY_ORIENTATION_270:
786 mOrientedXPrecision = mYPrecision;
787 mOrientedYPrecision = mXPrecision;
788
789 mOrientedRanges.x.min = 0;
790 mOrientedRanges.x.max = mDisplayHeight - 1;
791 mOrientedRanges.x.flat = 0;
792 mOrientedRanges.x.fuzz = 0;
793 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
794
795 mOrientedRanges.y.min = 0;
796 mOrientedRanges.y.max = mDisplayWidth - 1;
797 mOrientedRanges.y.flat = 0;
798 mOrientedRanges.y.fuzz = 0;
799 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
800 break;
801
802 default:
803 mOrientedXPrecision = mXPrecision;
804 mOrientedYPrecision = mYPrecision;
805
806 mOrientedRanges.x.min = 0;
807 mOrientedRanges.x.max = mDisplayWidth - 1;
808 mOrientedRanges.x.flat = 0;
809 mOrientedRanges.x.fuzz = 0;
810 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
811
812 mOrientedRanges.y.min = 0;
813 mOrientedRanges.y.max = mDisplayHeight - 1;
814 mOrientedRanges.y.flat = 0;
815 mOrientedRanges.y.fuzz = 0;
816 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
817 break;
818 }
819}
820
Prabir Pradhan1728b212021-10-19 16:00:03 -0700821void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000822 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700823
824 resolveExternalStylusPresence();
825
826 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100827 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000828 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700829 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100830 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700831 if (hasStylus()) {
832 mSource |= AINPUT_SOURCE_STYLUS;
833 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800834 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700835 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100836 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700837 if (hasStylus()) {
838 mSource |= AINPUT_SOURCE_STYLUS;
839 }
840 if (hasExternalStylus()) {
841 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
842 }
Michael Wright227c5542020-07-02 18:30:52 +0100843 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700844 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100845 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700846 } else {
847 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100848 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700849 }
850
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000851 const std::optional<DisplayViewport> newViewportOpt = findViewport();
852
853 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700854 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
855 ALOGW("Touch device '%s' did not report support for X or Y axis! "
856 "The device will be inoperable.",
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) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700860 ALOGI("Touch device '%s' could not query the properties of its associated "
861 "display. The device will be inoperable until the display size "
862 "becomes available.",
863 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100864 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700865 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000866 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
867 getDeviceName().c_str(), getDeviceId());
868 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000869 }
870
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700871 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700872 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
873 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000874 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
875 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
876 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
877 const float rawMeanResolution =
878 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700879
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000880 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
881 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700882 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700883 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000884 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
885 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
886 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700887
Michael Wright227c5542020-07-02 18:30:52 +0100888 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700889 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700890 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
891 int32_t naturalPhysicalLeft, naturalPhysicalTop;
892 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700893
Prabir Pradhan1728b212021-10-19 16:00:03 -0700894 // Apply the inverse of the input device orientation so that the input device is
895 // configured in the same orientation as the viewport. The input device orientation will
896 // be re-applied by mInputDeviceOrientation.
897 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700898 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700899 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700900 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700901 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
902 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800903 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 naturalPhysicalTop = mViewport.physicalLeft;
905 naturalDeviceWidth = mViewport.deviceHeight;
906 naturalDeviceHeight = mViewport.deviceWidth;
907 break;
908 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700909 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
910 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
911 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
912 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
913 naturalDeviceWidth = mViewport.deviceWidth;
914 naturalDeviceHeight = mViewport.deviceHeight;
915 break;
916 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700917 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
918 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
919 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800920 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700921 naturalDeviceWidth = mViewport.deviceHeight;
922 naturalDeviceHeight = mViewport.deviceWidth;
923 break;
924 case DISPLAY_ORIENTATION_0:
925 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700926 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
927 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
928 naturalPhysicalLeft = mViewport.physicalLeft;
929 naturalPhysicalTop = mViewport.physicalTop;
930 naturalDeviceWidth = mViewport.deviceWidth;
931 naturalDeviceHeight = mViewport.deviceHeight;
932 break;
933 }
934
935 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
936 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
937 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
938 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
939 }
940
941 mPhysicalWidth = naturalPhysicalWidth;
942 mPhysicalHeight = naturalPhysicalHeight;
943 mPhysicalLeft = naturalPhysicalLeft;
944 mPhysicalTop = naturalPhysicalTop;
945
Prabir Pradhan1728b212021-10-19 16:00:03 -0700946 const int32_t oldDisplayWidth = mDisplayWidth;
947 const int32_t oldDisplayHeight = mDisplayHeight;
948 mDisplayWidth = naturalDeviceWidth;
949 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700950
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000951 // InputReader works in the un-rotated display coordinate space, so we don't need to do
952 // anything if the device is already orientation-aware. If the device is not
953 // orientation-aware, then we need to apply the inverse rotation of the display so that
954 // when the display rotation is applied later as a part of the per-window transform, we
955 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700956 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000957 ? DISPLAY_ORIENTATION_0
958 : getInverseRotation(mViewport.orientation);
959 // For orientation-aware devices that work in the un-rotated coordinate space, the
960 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000961 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
962 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
963 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700964
965 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700966 mInputDeviceOrientation =
967 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700968 } else {
969 mPhysicalWidth = rawWidth;
970 mPhysicalHeight = rawHeight;
971 mPhysicalLeft = 0;
972 mPhysicalTop = 0;
973
Prabir Pradhan1728b212021-10-19 16:00:03 -0700974 mDisplayWidth = rawWidth;
975 mDisplayHeight = rawHeight;
976 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977 }
978 }
979
980 // If moving between pointer modes, need to reset some state.
981 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
982 if (deviceModeChanged) {
983 mOrientedRanges.clear();
984 }
985
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800986 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
987 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100988 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800989 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000990 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
991 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800992 if (mPointerController == nullptr) {
993 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000995 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800996 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
997 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700998 } else {
lilinnandef700b2022-06-17 19:32:01 +0800999 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1000 !mConfig.showTouches) {
1001 mPointerController->clearSpots();
1002 }
Michael Wright17db18e2020-06-26 20:51:44 +01001003 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004 }
1005
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001006 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001007 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1008 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001009 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1010 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001012 configureVirtualKeys();
1013
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001014 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001015
1016 // Location
1017 updateAffineTransformation();
1018
Michael Wright227c5542020-07-02 18:30:52 +01001019 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001020 // Compute pointer gesture detection parameters.
1021 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001022 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023
1024 // Scale movements such that one whole swipe of the touch pad covers a
1025 // given area relative to the diagonal size of the display when no acceleration
1026 // is applied.
1027 // Assume that the touch pad has a square aspect ratio such that movements in
1028 // X and Y of the same number of raw units cover the same physical distance.
1029 mPointerXMovementScale =
1030 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1031 mPointerYMovementScale = mPointerXMovementScale;
1032
1033 // Scale zooms to cover a smaller range of the display than movements do.
1034 // This value determines the area around the pointer that is affected by freeform
1035 // pointer gestures.
1036 mPointerXZoomScale =
1037 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1038 mPointerYZoomScale = mPointerXZoomScale;
1039
HQ Liue6983c72022-04-19 22:14:56 +00001040 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1041 // axis is non positive value.
1042 const float minFreeformGestureWidth =
1043 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1044
1045 mPointerGestureMaxSwipeWidth =
1046 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1047 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001048 }
1049
1050 // Inform the dispatcher about the changes.
1051 *outResetNeeded = true;
1052 bumpGeneration();
1053 }
1054}
1055
Prabir Pradhan1728b212021-10-19 16:00:03 -07001056void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001058 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1059 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001060 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1061 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1062 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1063 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001064 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001065}
1066
1067void TouchInputMapper::configureVirtualKeys() {
1068 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001069 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001070
1071 mVirtualKeys.clear();
1072
1073 if (virtualKeyDefinitions.size() == 0) {
1074 return;
1075 }
1076
1077 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1078 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1079 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1080 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1081
1082 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1083 VirtualKey virtualKey;
1084
1085 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1086 int32_t keyCode;
1087 int32_t dummyKeyMetaState;
1088 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001089 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1090 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1092 continue; // drop the key
1093 }
1094
1095 virtualKey.keyCode = keyCode;
1096 virtualKey.flags = flags;
1097
1098 // convert the key definition's display coordinates into touch coordinates for a hit box
1099 int32_t halfWidth = virtualKeyDefinition.width / 2;
1100 int32_t halfHeight = virtualKeyDefinition.height / 2;
1101
1102 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001103 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104 touchScreenLeft;
1105 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001106 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001107 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001108 virtualKey.hitTop =
1109 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001111 virtualKey.hitBottom =
1112 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 touchScreenTop;
1114 mVirtualKeys.push_back(virtualKey);
1115 }
1116}
1117
1118void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1119 if (!mVirtualKeys.empty()) {
1120 dump += INDENT3 "Virtual Keys:\n";
1121
1122 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1123 const VirtualKey& virtualKey = mVirtualKeys[i];
1124 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1125 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1126 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1127 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1128 }
1129 }
1130}
1131
1132void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001133 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001134 Calibration& out = mCalibration;
1135
1136 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001137 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001138 std::string sizeCalibrationString;
1139 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001140 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001141 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001145 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001147 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001149 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001151 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001152 }
1153 }
1154
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001155 float sizeScale;
1156
1157 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1158 out.sizeScale = sizeScale;
1159 }
1160 float sizeBias;
1161 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1162 out.sizeBias = sizeBias;
1163 }
1164 bool sizeIsSummed;
1165 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1166 out.sizeIsSummed = sizeIsSummed;
1167 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168
1169 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001171 std::string pressureCalibrationString;
1172 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001173 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001174 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001176 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001178 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 } else if (pressureCalibrationString != "default") {
1180 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001181 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 }
1183 }
1184
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001185 float pressureScale;
1186 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1187 out.pressureScale = pressureScale;
1188 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189
1190 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001192 std::string orientationCalibrationString;
1193 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001194 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (orientationCalibrationString != "default") {
1201 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001202 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 }
1204 }
1205
1206 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001208 std::string distanceCalibrationString;
1209 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 } else if (distanceCalibrationString != "default") {
1215 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001216 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 }
1218 }
1219
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001220 float distanceScale;
1221 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1222 out.distanceScale = distanceScale;
1223 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224
Michael Wright227c5542020-07-02 18:30:52 +01001225 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001226 std::string coverageCalibrationString;
1227 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001229 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001231 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 } else if (coverageCalibrationString != "default") {
1233 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001234 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235 }
1236 }
1237}
1238
1239void TouchInputMapper::resolveCalibration() {
1240 // Size
1241 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001242 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1243 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 }
1245 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001246 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 }
1248
1249 // Pressure
1250 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001251 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1252 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 }
1254 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001255 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256 }
1257
1258 // Orientation
1259 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001260 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1261 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001264 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 }
1266
1267 // Distance
1268 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001269 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1270 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001273 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274 }
1275
1276 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001277 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1278 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 }
1280}
1281
1282void TouchInputMapper::dumpCalibration(std::string& dump) {
1283 dump += INDENT3 "Calibration:\n";
1284
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001285 dump += INDENT4 "touch.size.calibration: ";
1286 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001288 if (mCalibration.sizeScale) {
1289 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 }
1291
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001292 if (mCalibration.sizeBias) {
1293 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 }
1295
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001296 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001298 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 }
1300
1301 // Pressure
1302 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001303 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += INDENT4 "touch.pressure.calibration: none\n";
1305 break;
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.pressure.calibration: physical\n";
1308 break;
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1311 break;
1312 default:
1313 ALOG_ASSERT(false);
1314 }
1315
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001316 if (mCalibration.pressureScale) {
1317 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 }
1319
1320 // Orientation
1321 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001322 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001323 dump += INDENT4 "touch.orientation.calibration: none\n";
1324 break;
Michael Wright227c5542020-07-02 18:30:52 +01001325 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1327 break;
Michael Wright227c5542020-07-02 18:30:52 +01001328 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 dump += INDENT4 "touch.orientation.calibration: vector\n";
1330 break;
1331 default:
1332 ALOG_ASSERT(false);
1333 }
1334
1335 // Distance
1336 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001337 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 dump += INDENT4 "touch.distance.calibration: none\n";
1339 break;
Michael Wright227c5542020-07-02 18:30:52 +01001340 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.distance.calibration: scaled\n";
1342 break;
1343 default:
1344 ALOG_ASSERT(false);
1345 }
1346
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001347 if (mCalibration.distanceScale) {
1348 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349 }
1350
1351 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001352 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 dump += INDENT4 "touch.coverage.calibration: none\n";
1354 break;
Michael Wright227c5542020-07-02 18:30:52 +01001355 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356 dump += INDENT4 "touch.coverage.calibration: box\n";
1357 break;
1358 default:
1359 ALOG_ASSERT(false);
1360 }
1361}
1362
1363void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1364 dump += INDENT3 "Affine Transformation:\n";
1365
1366 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1367 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1368 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1369 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1370 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1371 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1372}
1373
1374void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001375 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001376 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001377}
1378
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001379std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001380 std::list<NotifyArgs> out = cancelTouch(when, when);
1381 updateTouchSpots();
1382
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001383 mCursorButtonAccumulator.reset(getDeviceContext());
1384 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001385 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386
1387 mPointerVelocityControl.reset();
1388 mWheelXVelocityControl.reset();
1389 mWheelYVelocityControl.reset();
1390
1391 mRawStatesPending.clear();
1392 mCurrentRawState.clear();
1393 mCurrentCookedState.clear();
1394 mLastRawState.clear();
1395 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001396 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001397 mSentHoverEnter = false;
1398 mHavePointerIds = false;
1399 mCurrentMotionAborted = false;
1400 mDownTime = 0;
1401
1402 mCurrentVirtualKey.down = false;
1403
1404 mPointerGesture.reset();
1405 mPointerSimple.reset();
1406 resetExternalStylus();
1407
1408 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001409 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410 mPointerController->clearSpots();
1411 }
1412
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001413 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001414}
1415
1416void TouchInputMapper::resetExternalStylus() {
1417 mExternalStylusState.clear();
1418 mExternalStylusId = -1;
1419 mExternalStylusFusionTimeout = LLONG_MAX;
1420 mExternalStylusDataPending = false;
1421}
1422
1423void TouchInputMapper::clearStylusDataPendingFlags() {
1424 mExternalStylusDataPending = false;
1425 mExternalStylusFusionTimeout = LLONG_MAX;
1426}
1427
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001428std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001429 mCursorButtonAccumulator.process(rawEvent);
1430 mCursorScrollAccumulator.process(rawEvent);
1431 mTouchButtonAccumulator.process(rawEvent);
1432
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001433 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001434 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001435 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001437 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438}
1439
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001440std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1441 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001442 if (mDeviceMode == DeviceMode::DISABLED) {
1443 // Only save the last pending state when the device is disabled.
1444 mRawStatesPending.clear();
1445 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446 // Push a new state.
1447 mRawStatesPending.emplace_back();
1448
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001449 RawState& next = mRawStatesPending.back();
1450 next.clear();
1451 next.when = when;
1452 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001453
1454 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001455 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1457
1458 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001459 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1460 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001461 mCursorScrollAccumulator.finishSync();
1462
1463 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001464 syncTouch(when, &next);
1465
1466 // The last RawState is the actually second to last, since we just added a new state
1467 const RawState& last =
1468 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001469
1470 // Assign pointer ids.
1471 if (!mHavePointerIds) {
1472 assignPointerIds(last, next);
1473 }
1474
Harry Cutts45483602022-08-24 14:36:48 +00001475 ALOGD_IF(DEBUG_RAW_EVENTS,
1476 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1477 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1478 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1479 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1480 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1481 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001482
Arthur Hung9ad18942021-06-19 02:04:46 +00001483 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1484 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1485 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1486 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1487 next.rawPointerData.hoveringIdBits.value);
1488 }
1489
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001490 out += processRawTouches(false /*timeout*/);
1491 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001492}
1493
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001494std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1495 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001496 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001497 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001498 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001499 }
1500
1501 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1502 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1503 // touching the current state will only observe the events that have been dispatched to the
1504 // rest of the pipeline.
1505 const size_t N = mRawStatesPending.size();
1506 size_t count;
1507 for (count = 0; count < N; count++) {
1508 const RawState& next = mRawStatesPending[count];
1509
1510 // A failure to assign the stylus id means that we're waiting on stylus data
1511 // and so should defer the rest of the pipeline.
1512 if (assignExternalStylusId(next, timeout)) {
1513 break;
1514 }
1515
1516 // All ready to go.
1517 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001518 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001519 if (mCurrentRawState.when < mLastRawState.when) {
1520 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001521 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001523 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 }
1525 if (count != 0) {
1526 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1527 }
1528
1529 if (mExternalStylusDataPending) {
1530 if (timeout) {
1531 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1532 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001533 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001534 ALOGD_IF(DEBUG_STYLUS_FUSION,
1535 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001536 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001537 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001538 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1539 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1540 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1541 }
1542 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001543 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001544}
1545
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001546std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1547 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001548 // Always start with a clean state.
1549 mCurrentCookedState.clear();
1550
1551 // Apply stylus buttons to current raw state.
1552 applyExternalStylusButtonState(when);
1553
1554 // Handle policy on initial down or hover events.
1555 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1556 mCurrentRawState.rawPointerData.pointerCount != 0;
1557
1558 uint32_t policyFlags = 0;
1559 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1560 if (initialDown || buttonsPressed) {
1561 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001562 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001563 getContext()->fadePointer();
1564 }
1565
1566 if (mParameters.wake) {
1567 policyFlags |= POLICY_FLAG_WAKE;
1568 }
1569 }
1570
1571 // Consume raw off-screen touches before cooking pointer data.
1572 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001573 bool consumed;
1574 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1575 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576 mCurrentRawState.rawPointerData.clear();
1577 }
1578
1579 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1580 // with cooked pointer data that has the same ids and indices as the raw data.
1581 // The following code can use either the raw or cooked data, as needed.
1582 cookPointerData();
1583
1584 // Apply stylus pressure to current cooked state.
1585 applyExternalStylusTouchState(when);
1586
1587 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001588 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1589 mSource, mViewport.displayId, policyFlags,
1590 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591
1592 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001593 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001594 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1595 uint32_t id = idBits.clearFirstMarkedBit();
1596 const RawPointerData::Pointer& pointer =
1597 mCurrentRawState.rawPointerData.pointerForId(id);
1598 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1599 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1600 mCurrentCookedState.stylusIdBits.markBit(id);
1601 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1602 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1603 mCurrentCookedState.fingerIdBits.markBit(id);
1604 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1605 mCurrentCookedState.mouseIdBits.markBit(id);
1606 }
1607 }
1608 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1609 uint32_t id = idBits.clearFirstMarkedBit();
1610 const RawPointerData::Pointer& pointer =
1611 mCurrentRawState.rawPointerData.pointerForId(id);
1612 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1613 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1614 mCurrentCookedState.stylusIdBits.markBit(id);
1615 }
1616 }
1617
1618 // Stylus takes precedence over all tools, then mouse, then finger.
1619 PointerUsage pointerUsage = mPointerUsage;
1620 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1621 mCurrentCookedState.mouseIdBits.clear();
1622 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001623 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1625 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001626 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1628 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001629 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 }
1631
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001632 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001633 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001635 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001636 out += dispatchButtonRelease(when, readTime, policyFlags);
1637 out += dispatchHoverExit(when, readTime, policyFlags);
1638 out += dispatchTouches(when, readTime, policyFlags);
1639 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1640 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001641 }
1642
1643 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1644 mCurrentMotionAborted = false;
1645 }
1646 }
1647
1648 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001649 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1650 mSource, mViewport.displayId, policyFlags,
1651 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001652
1653 // Clear some transient state.
1654 mCurrentRawState.rawVScroll = 0;
1655 mCurrentRawState.rawHScroll = 0;
1656
1657 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001658 mLastRawState = mCurrentRawState;
1659 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001660 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001661}
1662
Garfield Tanc734e4f2021-01-15 20:01:39 -08001663void TouchInputMapper::updateTouchSpots() {
1664 if (!mConfig.showTouches || mPointerController == nullptr) {
1665 return;
1666 }
1667
1668 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1669 // clear touch spots.
1670 if (mDeviceMode != DeviceMode::DIRECT &&
1671 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1672 return;
1673 }
1674
1675 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1676 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1677
1678 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001679 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1680 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001681 mCurrentCookedState.cookedPointerData.touchingIdBits,
1682 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001683}
1684
1685bool TouchInputMapper::isTouchScreen() {
1686 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1687 mParameters.hasAssociatedDisplay;
1688}
1689
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001690void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001691 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001692 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1693 }
1694}
1695
1696void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1697 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1698 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1699
1700 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1701 float pressure = mExternalStylusState.pressure;
1702 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1703 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1704 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1705 }
1706 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1707 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1708
1709 PointerProperties& properties =
1710 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1711 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1712 properties.toolType = mExternalStylusState.toolType;
1713 }
1714 }
1715}
1716
1717bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001718 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001719 return false;
1720 }
1721
1722 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1723 state.rawPointerData.pointerCount != 0;
1724 if (initialDown) {
1725 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001726 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001727 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1728 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001729 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001730 resetExternalStylus();
1731 } else {
1732 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1733 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1734 }
Harry Cutts45483602022-08-24 14:36:48 +00001735 ALOGD_IF(DEBUG_STYLUS_FUSION,
1736 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1737 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001738 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1739 return true;
1740 }
1741 }
1742
1743 // Check if the stylus pointer has gone up.
1744 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001745 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001746 mExternalStylusId = -1;
1747 }
1748
1749 return false;
1750}
1751
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001752std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1753 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001754 if (mDeviceMode == DeviceMode::POINTER) {
1755 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001756 // Since this is a synthetic event, we can consider its latency to be zero
1757 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001758 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001759 }
Michael Wright227c5542020-07-02 18:30:52 +01001760 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001761 if (mExternalStylusFusionTimeout < when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001762 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001763 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1764 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1765 }
1766 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001767 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001768}
1769
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001770std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1771 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001772 mExternalStylusState.copyFrom(state);
1773 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1774 // We're either in the middle of a fused stream of data or we're waiting on data before
1775 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1776 // data.
1777 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001778 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001779 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001780 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001781}
1782
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001783std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1784 uint32_t policyFlags, bool& outConsumed) {
1785 outConsumed = false;
1786 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001787 // Check for release of a virtual key.
1788 if (mCurrentVirtualKey.down) {
1789 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1790 // Pointer went up while virtual key was down.
1791 mCurrentVirtualKey.down = false;
1792 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001793 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1794 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1795 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001796 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1797 AKEY_EVENT_FLAG_FROM_SYSTEM |
1798 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001799 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001800 outConsumed = true;
1801 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001802 }
1803
1804 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1805 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1806 const RawPointerData::Pointer& pointer =
1807 mCurrentRawState.rawPointerData.pointerForId(id);
1808 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1809 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1810 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001811 outConsumed = true;
1812 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001813 }
1814 }
1815
1816 // Pointer left virtual key area or another pointer also went down.
1817 // Send key cancellation but do not consume the touch yet.
1818 // This is useful when the user swipes through from the virtual key area
1819 // into the main display surface.
1820 mCurrentVirtualKey.down = false;
1821 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001822 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1823 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001824 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1825 AKEY_EVENT_FLAG_FROM_SYSTEM |
1826 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1827 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001828 }
1829 }
1830
1831 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1832 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1833 // Pointer just went down. Check for virtual key press or off-screen touches.
1834 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1835 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001836 // Skip checking whether the pointer is inside the physical frame if the device is in
1837 // unscaled mode.
1838 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1839 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001840 // If exactly one pointer went down, check for virtual key hit.
1841 // Otherwise we will drop the entire stroke.
1842 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1843 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1844 if (virtualKey) {
1845 mCurrentVirtualKey.down = true;
1846 mCurrentVirtualKey.downTime = when;
1847 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1848 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1849 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001850 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1851 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001852
1853 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001854 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1855 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1856 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001857 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1858 AKEY_EVENT_ACTION_DOWN,
1859 AKEY_EVENT_FLAG_FROM_SYSTEM |
1860 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001861 }
1862 }
1863 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001864 outConsumed = true;
1865 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001866 }
1867 }
1868
1869 // Disable all virtual key touches that happen within a short time interval of the
1870 // most recent touch within the screen area. The idea is to filter out stray
1871 // virtual key presses when interacting with the touch screen.
1872 //
1873 // Problems we're trying to solve:
1874 //
1875 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1876 // virtual key area that is implemented by a separate touch panel and accidentally
1877 // triggers a virtual key.
1878 //
1879 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1880 // area and accidentally triggers a virtual key. This often happens when virtual keys
1881 // are layed out below the screen near to where the on screen keyboard's space bar
1882 // is displayed.
1883 if (mConfig.virtualKeyQuietTime > 0 &&
1884 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001885 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001886 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001887 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001888}
1889
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001890NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1891 uint32_t policyFlags, int32_t keyEventAction,
1892 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001893 int32_t keyCode = mCurrentVirtualKey.keyCode;
1894 int32_t scanCode = mCurrentVirtualKey.scanCode;
1895 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001896 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001897 policyFlags |= POLICY_FLAG_VIRTUAL;
1898
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001899 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1900 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1901 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001902}
1903
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001904std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1905 uint32_t policyFlags) {
1906 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001907 if (mCurrentMotionAborted) {
1908 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001909 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001910 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001911 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1912 if (!currentIdBits.isEmpty()) {
1913 int32_t metaState = getContext()->getGlobalMetaState();
1914 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001915 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001916 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1917 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001918 mCurrentCookedState.cookedPointerData.pointerProperties,
1919 mCurrentCookedState.cookedPointerData.pointerCoords,
1920 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1921 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1922 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001923 mCurrentMotionAborted = true;
1924 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001925 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926}
1927
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001928// Updates pointer coords and properties for pointers with specified ids that have moved.
1929// Returns true if any of them changed.
1930static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1931 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1932 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1933 BitSet32 idBits) {
1934 bool changed = false;
1935 while (!idBits.isEmpty()) {
1936 uint32_t id = idBits.clearFirstMarkedBit();
1937 uint32_t inIndex = inIdToIndex[id];
1938 uint32_t outIndex = outIdToIndex[id];
1939
1940 const PointerProperties& curInProperties = inProperties[inIndex];
1941 const PointerCoords& curInCoords = inCoords[inIndex];
1942 PointerProperties& curOutProperties = outProperties[outIndex];
1943 PointerCoords& curOutCoords = outCoords[outIndex];
1944
1945 if (curInProperties != curOutProperties) {
1946 curOutProperties.copyFrom(curInProperties);
1947 changed = true;
1948 }
1949
1950 if (curInCoords != curOutCoords) {
1951 curOutCoords.copyFrom(curInCoords);
1952 changed = true;
1953 }
1954 }
1955 return changed;
1956}
1957
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001958std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1959 uint32_t policyFlags) {
1960 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001961 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1962 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1963 int32_t metaState = getContext()->getGlobalMetaState();
1964 int32_t buttonState = mCurrentCookedState.buttonState;
1965
1966 if (currentIdBits == lastIdBits) {
1967 if (!currentIdBits.isEmpty()) {
1968 // No pointer id changes so this is a move event.
1969 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001970 out.push_back(
1971 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1972 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1973 mCurrentCookedState.cookedPointerData.pointerProperties,
1974 mCurrentCookedState.cookedPointerData.pointerCoords,
1975 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1976 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1977 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001978 }
1979 } else {
1980 // There may be pointers going up and pointers going down and pointers moving
1981 // all at the same time.
1982 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1983 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1984 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1985 BitSet32 dispatchedIdBits(lastIdBits.value);
1986
1987 // Update last coordinates of pointers that have moved so that we observe the new
1988 // pointer positions at the same time as other pointers that have just gone up.
1989 bool moveNeeded =
1990 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1991 mCurrentCookedState.cookedPointerData.pointerCoords,
1992 mCurrentCookedState.cookedPointerData.idToIndex,
1993 mLastCookedState.cookedPointerData.pointerProperties,
1994 mLastCookedState.cookedPointerData.pointerCoords,
1995 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1996 if (buttonState != mLastCookedState.buttonState) {
1997 moveNeeded = true;
1998 }
1999
2000 // Dispatch pointer up events.
2001 while (!upIdBits.isEmpty()) {
2002 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002003 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002004 if (isCanceled) {
2005 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2006 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002007 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2008 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2009 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2010 buttonState, 0,
2011 mLastCookedState.cookedPointerData.pointerProperties,
2012 mLastCookedState.cookedPointerData.pointerCoords,
2013 mLastCookedState.cookedPointerData.idToIndex,
2014 dispatchedIdBits, upId, mOrientedXPrecision,
2015 mOrientedYPrecision, mDownTime,
2016 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002017 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002018 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002019 }
2020
2021 // Dispatch move events if any of the remaining pointers moved from their old locations.
2022 // Although applications receive new locations as part of individual pointer up
2023 // events, they do not generally handle them except when presented in a move event.
2024 if (moveNeeded && !moveIdBits.isEmpty()) {
2025 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002026 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2027 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2028 mCurrentCookedState.cookedPointerData.pointerProperties,
2029 mCurrentCookedState.cookedPointerData.pointerCoords,
2030 mCurrentCookedState.cookedPointerData.idToIndex,
2031 dispatchedIdBits, -1, mOrientedXPrecision,
2032 mOrientedYPrecision, mDownTime,
2033 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002034 }
2035
2036 // Dispatch pointer down events using the new pointer locations.
2037 while (!downIdBits.isEmpty()) {
2038 uint32_t downId = downIdBits.clearFirstMarkedBit();
2039 dispatchedIdBits.markBit(downId);
2040
2041 if (dispatchedIdBits.count() == 1) {
2042 // First pointer is going down. Set down time.
2043 mDownTime = when;
2044 }
2045
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002046 out.push_back(
2047 dispatchMotion(when, readTime, policyFlags, mSource,
2048 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2049 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2050 mCurrentCookedState.cookedPointerData.pointerCoords,
2051 mCurrentCookedState.cookedPointerData.idToIndex,
2052 dispatchedIdBits, downId, mOrientedXPrecision,
2053 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002054 }
2055 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002056 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002057}
2058
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002059std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2060 uint32_t policyFlags) {
2061 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002062 if (mSentHoverEnter &&
2063 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2064 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2065 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002066 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2067 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2068 mLastCookedState.buttonState, 0,
2069 mLastCookedState.cookedPointerData.pointerProperties,
2070 mLastCookedState.cookedPointerData.pointerCoords,
2071 mLastCookedState.cookedPointerData.idToIndex,
2072 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2073 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2074 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002075 mSentHoverEnter = false;
2076 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002077 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002078}
2079
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002080std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2081 uint32_t policyFlags) {
2082 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002083 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2084 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2085 int32_t metaState = getContext()->getGlobalMetaState();
2086 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002087 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2088 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2089 mCurrentRawState.buttonState, 0,
2090 mCurrentCookedState.cookedPointerData.pointerProperties,
2091 mCurrentCookedState.cookedPointerData.pointerCoords,
2092 mCurrentCookedState.cookedPointerData.idToIndex,
2093 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2094 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2095 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002096 mSentHoverEnter = true;
2097 }
2098
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002099 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2100 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2101 mCurrentRawState.buttonState, 0,
2102 mCurrentCookedState.cookedPointerData.pointerProperties,
2103 mCurrentCookedState.cookedPointerData.pointerCoords,
2104 mCurrentCookedState.cookedPointerData.idToIndex,
2105 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2106 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2107 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002108 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002109 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110}
2111
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002112std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2113 uint32_t policyFlags) {
2114 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002115 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2116 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2117 const int32_t metaState = getContext()->getGlobalMetaState();
2118 int32_t buttonState = mLastCookedState.buttonState;
2119 while (!releasedButtons.isEmpty()) {
2120 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2121 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002122 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2123 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2124 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002125 mLastCookedState.cookedPointerData.pointerProperties,
2126 mLastCookedState.cookedPointerData.pointerCoords,
2127 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002128 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2129 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002130 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002131 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002132}
2133
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002134std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2135 uint32_t policyFlags) {
2136 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002137 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2138 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2139 const int32_t metaState = getContext()->getGlobalMetaState();
2140 int32_t buttonState = mLastCookedState.buttonState;
2141 while (!pressedButtons.isEmpty()) {
2142 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2143 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002144 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2145 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2146 buttonState, 0,
2147 mCurrentCookedState.cookedPointerData.pointerProperties,
2148 mCurrentCookedState.cookedPointerData.pointerCoords,
2149 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2150 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2151 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002152 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002153 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154}
2155
2156const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2157 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2158 return cookedPointerData.touchingIdBits;
2159 }
2160 return cookedPointerData.hoveringIdBits;
2161}
2162
2163void TouchInputMapper::cookPointerData() {
2164 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2165
2166 mCurrentCookedState.cookedPointerData.clear();
2167 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2168 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2169 mCurrentRawState.rawPointerData.hoveringIdBits;
2170 mCurrentCookedState.cookedPointerData.touchingIdBits =
2171 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002172 mCurrentCookedState.cookedPointerData.canceledIdBits =
2173 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002174
2175 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2176 mCurrentCookedState.buttonState = 0;
2177 } else {
2178 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2179 }
2180
2181 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002182 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002183 for (uint32_t i = 0; i < currentPointerCount; i++) {
2184 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2185
2186 // Size
2187 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2188 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002189 case Calibration::SizeCalibration::GEOMETRIC:
2190 case Calibration::SizeCalibration::DIAMETER:
2191 case Calibration::SizeCalibration::BOX:
2192 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002193 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2194 touchMajor = in.touchMajor;
2195 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2196 toolMajor = in.toolMajor;
2197 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2198 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2199 : in.touchMajor;
2200 } else if (mRawPointerAxes.touchMajor.valid) {
2201 toolMajor = touchMajor = in.touchMajor;
2202 toolMinor = touchMinor =
2203 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2204 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2205 : in.touchMajor;
2206 } else if (mRawPointerAxes.toolMajor.valid) {
2207 touchMajor = toolMajor = in.toolMajor;
2208 touchMinor = toolMinor =
2209 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2210 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2211 : in.toolMajor;
2212 } else {
2213 ALOG_ASSERT(false,
2214 "No touch or tool axes. "
2215 "Size calibration should have been resolved to NONE.");
2216 touchMajor = 0;
2217 touchMinor = 0;
2218 toolMajor = 0;
2219 toolMinor = 0;
2220 size = 0;
2221 }
2222
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002223 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002224 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2225 if (touchingCount > 1) {
2226 touchMajor /= touchingCount;
2227 touchMinor /= touchingCount;
2228 toolMajor /= touchingCount;
2229 toolMinor /= touchingCount;
2230 size /= touchingCount;
2231 }
2232 }
2233
Michael Wright227c5542020-07-02 18:30:52 +01002234 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002235 touchMajor *= mGeometricScale;
2236 touchMinor *= mGeometricScale;
2237 toolMajor *= mGeometricScale;
2238 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002239 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002240 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2241 touchMinor = touchMajor;
2242 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2243 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002244 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002245 touchMinor = touchMajor;
2246 toolMinor = toolMajor;
2247 }
2248
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002249 mCalibration.applySizeScaleAndBias(touchMajor);
2250 mCalibration.applySizeScaleAndBias(touchMinor);
2251 mCalibration.applySizeScaleAndBias(toolMajor);
2252 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002253 size *= mSizeScale;
2254 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002255 case Calibration::SizeCalibration::DEFAULT:
2256 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2257 break;
2258 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002259 touchMajor = 0;
2260 touchMinor = 0;
2261 toolMajor = 0;
2262 toolMinor = 0;
2263 size = 0;
2264 break;
2265 }
2266
2267 // Pressure
2268 float pressure;
2269 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002270 case Calibration::PressureCalibration::PHYSICAL:
2271 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002272 pressure = in.pressure * mPressureScale;
2273 break;
2274 default:
2275 pressure = in.isHovering ? 0 : 1;
2276 break;
2277 }
2278
2279 // Tilt and Orientation
2280 float tilt;
2281 float orientation;
2282 if (mHaveTilt) {
2283 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2284 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2285 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2286 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2287 } else {
2288 tilt = 0;
2289
2290 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002291 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 orientation = in.orientation * mOrientationScale;
2293 break;
Michael Wright227c5542020-07-02 18:30:52 +01002294 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002295 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2296 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2297 if (c1 != 0 || c2 != 0) {
2298 orientation = atan2f(c1, c2) * 0.5f;
2299 float confidence = hypotf(c1, c2);
2300 float scale = 1.0f + confidence / 16.0f;
2301 touchMajor *= scale;
2302 touchMinor /= scale;
2303 toolMajor *= scale;
2304 toolMinor /= scale;
2305 } else {
2306 orientation = 0;
2307 }
2308 break;
2309 }
2310 default:
2311 orientation = 0;
2312 }
2313 }
2314
2315 // Distance
2316 float distance;
2317 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002318 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002319 distance = in.distance * mDistanceScale;
2320 break;
2321 default:
2322 distance = 0;
2323 }
2324
2325 // Coverage
2326 int32_t rawLeft, rawTop, rawRight, rawBottom;
2327 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002328 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002329 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2330 rawRight = in.toolMinor & 0x0000ffff;
2331 rawBottom = in.toolMajor & 0x0000ffff;
2332 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2333 break;
2334 default:
2335 rawLeft = rawTop = rawRight = rawBottom = 0;
2336 break;
2337 }
2338
2339 // Adjust X,Y coords for device calibration
2340 // TODO: Adjust coverage coords?
2341 float xTransformed = in.x, yTransformed = in.y;
2342 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002343 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344
Prabir Pradhan1728b212021-10-19 16:00:03 -07002345 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002346 float left, top, right, bottom;
2347
Prabir Pradhan1728b212021-10-19 16:00:03 -07002348 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002350 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2351 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2352 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2353 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002355 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002357 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 }
2359 break;
2360 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2362 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002363 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2364 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002366 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002368 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 }
2370 break;
2371 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2373 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002374 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2375 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002376 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002377 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002379 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 }
2381 break;
2382 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002383 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2384 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2385 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2386 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 break;
2388 }
2389
2390 // Write output coords.
2391 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2392 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002393 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2394 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002395 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2396 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2397 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2398 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2400 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002402 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2404 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2405 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2406 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2407 } else {
2408 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2409 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2410 }
2411
Chris Ye364fdb52020-08-05 15:07:56 -07002412 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002413 uint32_t id = in.id;
2414 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2415 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2416 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2417 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2418 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2419 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2420 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2421 }
2422
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002423 // Write output properties.
2424 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 properties.clear();
2426 properties.id = id;
2427 properties.toolType = in.toolType;
2428
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002429 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002430 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002431 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 }
2433}
2434
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002435std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2436 uint32_t policyFlags,
2437 PointerUsage pointerUsage) {
2438 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002439 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002440 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002441 mPointerUsage = pointerUsage;
2442 }
2443
2444 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002445 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002446 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002447 break;
Michael Wright227c5542020-07-02 18:30:52 +01002448 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002449 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 break;
Michael Wright227c5542020-07-02 18:30:52 +01002451 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002452 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453 break;
Michael Wright227c5542020-07-02 18:30:52 +01002454 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002455 break;
2456 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002457 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458}
2459
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002460std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2461 uint32_t policyFlags) {
2462 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002464 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002465 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 break;
Michael Wright227c5542020-07-02 18:30:52 +01002467 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002468 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 break;
Michael Wright227c5542020-07-02 18:30:52 +01002470 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002471 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 break;
Michael Wright227c5542020-07-02 18:30:52 +01002473 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 break;
2475 }
2476
Michael Wright227c5542020-07-02 18:30:52 +01002477 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002478 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479}
2480
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002481std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2482 uint32_t policyFlags,
2483 bool isTimeout) {
2484 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 // Update current gesture coordinates.
2486 bool cancelPreviousGesture, finishPreviousGesture;
2487 bool sendEvents =
2488 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2489 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002490 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491 }
2492 if (finishPreviousGesture) {
2493 cancelPreviousGesture = false;
2494 }
2495
2496 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002497 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002498 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002499 if (finishPreviousGesture || cancelPreviousGesture) {
2500 mPointerController->clearSpots();
2501 }
2502
Michael Wright227c5542020-07-02 18:30:52 +01002503 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002504 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2505 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002506 mPointerGesture.currentGestureIdBits,
2507 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002508 }
2509 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002510 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 }
2512
2513 // Show or hide the pointer if needed.
2514 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002515 case PointerGesture::Mode::NEUTRAL:
2516 case PointerGesture::Mode::QUIET:
2517 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2518 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002519 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002520 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002521 }
2522 break;
Michael Wright227c5542020-07-02 18:30:52 +01002523 case PointerGesture::Mode::TAP:
2524 case PointerGesture::Mode::TAP_DRAG:
2525 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2526 case PointerGesture::Mode::HOVER:
2527 case PointerGesture::Mode::PRESS:
2528 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002529 // Unfade the pointer when the current gesture manipulates the
2530 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002531 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002532 break;
Michael Wright227c5542020-07-02 18:30:52 +01002533 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 // Fade the pointer when the current gesture manipulates a different
2535 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002536 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002537 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002538 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002539 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002540 }
2541 break;
2542 }
2543
2544 // Send events!
2545 int32_t metaState = getContext()->getGlobalMetaState();
2546 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002547 const MotionClassification classification =
2548 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2549 ? MotionClassification::TWO_FINGER_SWIPE
2550 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002551
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002552 uint32_t flags = 0;
2553
2554 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2555 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2556 }
2557
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002558 // Update last coordinates of pointers that have moved so that we observe the new
2559 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002560 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2561 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2562 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2563 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2564 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2565 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002566 bool moveNeeded = false;
2567 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2568 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2569 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2570 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2571 mPointerGesture.lastGestureIdBits.value);
2572 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2573 mPointerGesture.currentGestureCoords,
2574 mPointerGesture.currentGestureIdToIndex,
2575 mPointerGesture.lastGestureProperties,
2576 mPointerGesture.lastGestureCoords,
2577 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2578 if (buttonState != mLastCookedState.buttonState) {
2579 moveNeeded = true;
2580 }
2581 }
2582
2583 // Send motion events for all pointers that went up or were canceled.
2584 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2585 if (!dispatchedGestureIdBits.isEmpty()) {
2586 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002587 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002588 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002589 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002590 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2591 mPointerGesture.lastGestureProperties,
2592 mPointerGesture.lastGestureCoords,
2593 mPointerGesture.lastGestureIdToIndex,
2594 dispatchedGestureIdBits, -1, 0, 0,
2595 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002596
2597 dispatchedGestureIdBits.clear();
2598 } else {
2599 BitSet32 upGestureIdBits;
2600 if (finishPreviousGesture) {
2601 upGestureIdBits = dispatchedGestureIdBits;
2602 } else {
2603 upGestureIdBits.value =
2604 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2605 }
2606 while (!upGestureIdBits.isEmpty()) {
2607 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2608
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002609 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2610 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2611 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2612 mPointerGesture.lastGestureProperties,
2613 mPointerGesture.lastGestureCoords,
2614 mPointerGesture.lastGestureIdToIndex,
2615 dispatchedGestureIdBits, id, 0, 0,
2616 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002617
2618 dispatchedGestureIdBits.clearBit(id);
2619 }
2620 }
2621 }
2622
2623 // Send motion events for all pointers that moved.
2624 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002625 out.push_back(
2626 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2627 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2628 mPointerGesture.currentGestureProperties,
2629 mPointerGesture.currentGestureCoords,
2630 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2631 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002632 }
2633
2634 // Send motion events for all pointers that went down.
2635 if (down) {
2636 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2637 ~dispatchedGestureIdBits.value);
2638 while (!downGestureIdBits.isEmpty()) {
2639 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2640 dispatchedGestureIdBits.markBit(id);
2641
2642 if (dispatchedGestureIdBits.count() == 1) {
2643 mPointerGesture.downTime = when;
2644 }
2645
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002646 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2647 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2648 buttonState, 0, mPointerGesture.currentGestureProperties,
2649 mPointerGesture.currentGestureCoords,
2650 mPointerGesture.currentGestureIdToIndex,
2651 dispatchedGestureIdBits, id, 0, 0,
2652 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002653 }
2654 }
2655
2656 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002657 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002658 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2659 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2660 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2661 mPointerGesture.currentGestureProperties,
2662 mPointerGesture.currentGestureCoords,
2663 mPointerGesture.currentGestureIdToIndex,
2664 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2665 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002666 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2667 // Synthesize a hover move event after all pointers go up to indicate that
2668 // the pointer is hovering again even if the user is not currently touching
2669 // the touch pad. This ensures that a view will receive a fresh hover enter
2670 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002671 float x, y;
2672 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002673
2674 PointerProperties pointerProperties;
2675 pointerProperties.clear();
2676 pointerProperties.id = 0;
2677 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2678
2679 PointerCoords pointerCoords;
2680 pointerCoords.clear();
2681 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2682 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2683
2684 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002685 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2686 mSource, displayId, policyFlags,
2687 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2688 buttonState, MotionClassification::NONE,
2689 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2690 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2691 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002692 }
2693
2694 // Update state.
2695 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2696 if (!down) {
2697 mPointerGesture.lastGestureIdBits.clear();
2698 } else {
2699 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2700 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2701 uint32_t id = idBits.clearFirstMarkedBit();
2702 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2703 mPointerGesture.lastGestureProperties[index].copyFrom(
2704 mPointerGesture.currentGestureProperties[index]);
2705 mPointerGesture.lastGestureCoords[index].copyFrom(
2706 mPointerGesture.currentGestureCoords[index]);
2707 mPointerGesture.lastGestureIdToIndex[id] = index;
2708 }
2709 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002710 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002711}
2712
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002713std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2714 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002715 const MotionClassification classification =
2716 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2717 ? MotionClassification::TWO_FINGER_SWIPE
2718 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002719 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002720 // Cancel previously dispatches pointers.
2721 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2722 int32_t metaState = getContext()->getGlobalMetaState();
2723 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002724 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002725 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2726 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002727 mPointerGesture.lastGestureProperties,
2728 mPointerGesture.lastGestureCoords,
2729 mPointerGesture.lastGestureIdToIndex,
2730 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2731 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002732 }
2733
2734 // Reset the current pointer gesture.
2735 mPointerGesture.reset();
2736 mPointerVelocityControl.reset();
2737
2738 // Remove any current spots.
2739 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002740 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002741 mPointerController->clearSpots();
2742 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002743 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002744}
2745
2746bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2747 bool* outFinishPreviousGesture, bool isTimeout) {
2748 *outCancelPreviousGesture = false;
2749 *outFinishPreviousGesture = false;
2750
2751 // Handle TAP timeout.
2752 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002753 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002754
Michael Wright227c5542020-07-02 18:30:52 +01002755 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002756 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2757 // The tap/drag timeout has not yet expired.
2758 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2759 mConfig.pointerGestureTapDragInterval);
2760 } else {
2761 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002762 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002763 *outFinishPreviousGesture = true;
2764
2765 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002766 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002767 mPointerGesture.currentGestureIdBits.clear();
2768
2769 mPointerVelocityControl.reset();
2770 return true;
2771 }
2772 }
2773
2774 // We did not handle this timeout.
2775 return false;
2776 }
2777
2778 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2779 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2780
2781 // Update the velocity tracker.
2782 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002783 std::vector<float> positionsX;
2784 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002785 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002786 uint32_t id = idBits.clearFirstMarkedBit();
2787 const RawPointerData::Pointer& pointer =
2788 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002789 positionsX.push_back(pointer.x * mPointerXMovementScale);
2790 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002791 }
2792 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002793 {{AMOTION_EVENT_AXIS_X, positionsX},
2794 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 }
2796
2797 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2798 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002799 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2800 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2801 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002802 mPointerGesture.resetTap();
2803 }
2804
2805 // Pick a new active touch id if needed.
2806 // Choose an arbitrary pointer that just went down, if there is one.
2807 // Otherwise choose an arbitrary remaining pointer.
2808 // This guarantees we always have an active touch id when there is at least one pointer.
2809 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002810 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002811 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002812 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002813 mPointerGesture.firstTouchTime = when;
2814 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002815 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2816 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2817 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2818 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002819 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002820 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002821
2822 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002823 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002825 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2826 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2827 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002828 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002829 *outFinishPreviousGesture = true;
2830 }
2831
2832 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002833 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002834 mPointerGesture.currentGestureIdBits.clear();
2835
2836 mPointerVelocityControl.reset();
2837 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2838 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2839 // The pointer follows the active touch point.
2840 // Emit DOWN, MOVE, UP events at the pointer location.
2841 //
2842 // Only the active touch matters; other fingers are ignored. This policy helps
2843 // to handle the case where the user places a second finger on the touch pad
2844 // to apply the necessary force to depress an integrated button below the surface.
2845 // We don't want the second finger to be delivered to applications.
2846 //
2847 // For this to work well, we need to make sure to track the pointer that is really
2848 // active. If the user first puts one finger down to click then adds another
2849 // finger to drag then the active pointer should switch to the finger that is
2850 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002851 ALOGD_IF(DEBUG_GESTURES,
2852 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2853 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002855 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856 *outFinishPreviousGesture = true;
2857 mPointerGesture.activeGestureId = 0;
2858 }
2859
2860 // Switch pointers if needed.
2861 // Find the fastest pointer and follow it.
2862 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002863 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002864 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002865 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002866 ALOGD_IF(DEBUG_GESTURES,
2867 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2868 "bestSpeed=%0.3f",
2869 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002870 }
2871 }
2872
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002874 // When using spots, the click will occur at the position of the anchor
2875 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002876 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002877 } else {
2878 mPointerVelocityControl.reset();
2879 }
2880
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002881 float x, y;
2882 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002883
Michael Wright227c5542020-07-02 18:30:52 +01002884 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885 mPointerGesture.currentGestureIdBits.clear();
2886 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2887 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2888 mPointerGesture.currentGestureProperties[0].clear();
2889 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2890 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2891 mPointerGesture.currentGestureCoords[0].clear();
2892 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2893 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2894 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2895 } else if (currentFingerCount == 0) {
2896 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002897 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002898 *outFinishPreviousGesture = true;
2899 }
2900
2901 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2902 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2903 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002904 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2905 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906 lastFingerCount == 1) {
2907 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002908 float x, y;
2909 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2911 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002912 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913
2914 mPointerGesture.tapUpTime = when;
2915 getContext()->requestTimeoutAtTime(when +
2916 mConfig.pointerGestureTapDragInterval);
2917
2918 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002919 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 mPointerGesture.currentGestureIdBits.clear();
2921 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2922 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2923 mPointerGesture.currentGestureProperties[0].clear();
2924 mPointerGesture.currentGestureProperties[0].id =
2925 mPointerGesture.activeGestureId;
2926 mPointerGesture.currentGestureProperties[0].toolType =
2927 AMOTION_EVENT_TOOL_TYPE_FINGER;
2928 mPointerGesture.currentGestureCoords[0].clear();
2929 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2930 mPointerGesture.tapX);
2931 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2932 mPointerGesture.tapY);
2933 mPointerGesture.currentGestureCoords[0]
2934 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2935
2936 tapped = true;
2937 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002938 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2939 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002940 }
2941 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002942 if (DEBUG_GESTURES) {
2943 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2944 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2945 (when - mPointerGesture.tapDownTime) * 0.000001f);
2946 } else {
2947 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2948 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002949 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950 }
2951 }
2952
2953 mPointerVelocityControl.reset();
2954
2955 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002956 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002957 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002958 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002959 mPointerGesture.currentGestureIdBits.clear();
2960 }
2961 } else if (currentFingerCount == 1) {
2962 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2963 // The pointer follows the active touch point.
2964 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2965 // When in TAP_DRAG, emit MOVE events at the pointer location.
2966 ALOG_ASSERT(activeTouchId >= 0);
2967
Michael Wright227c5542020-07-02 18:30:52 +01002968 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2969 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002971 float x, y;
2972 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2974 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002975 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002976 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002977 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2978 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979 }
2980 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002981 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2982 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002983 }
Michael Wright227c5542020-07-02 18:30:52 +01002984 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2985 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 }
2987
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002990 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 } else {
2992 mPointerVelocityControl.reset();
2993 }
2994
2995 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002996 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002997 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002998 down = true;
2999 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003000 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003001 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003002 *outFinishPreviousGesture = true;
3003 }
3004 mPointerGesture.activeGestureId = 0;
3005 down = false;
3006 }
3007
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003008 float x, y;
3009 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003010
3011 mPointerGesture.currentGestureIdBits.clear();
3012 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3013 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3014 mPointerGesture.currentGestureProperties[0].clear();
3015 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3016 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3017 mPointerGesture.currentGestureCoords[0].clear();
3018 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3019 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3020 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3021 down ? 1.0f : 0.0f);
3022
3023 if (lastFingerCount == 0 && currentFingerCount != 0) {
3024 mPointerGesture.resetTap();
3025 mPointerGesture.tapDownTime = when;
3026 mPointerGesture.tapX = x;
3027 mPointerGesture.tapY = y;
3028 }
3029 } else {
3030 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003031 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003032 }
3033
3034 mPointerController->setButtonState(mCurrentRawState.buttonState);
3035
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003036 if (DEBUG_GESTURES) {
3037 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3038 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3039 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3040 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3041 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3042 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3043 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3044 uint32_t id = idBits.clearFirstMarkedBit();
3045 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3046 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3047 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3048 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3049 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3050 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3051 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3052 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3053 }
3054 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3055 uint32_t id = idBits.clearFirstMarkedBit();
3056 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3057 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3058 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3059 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3060 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3061 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3062 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3063 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3064 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003065 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003066 return true;
3067}
3068
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003069bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3070 if (mPointerGesture.activeTouchId < 0) {
3071 mPointerGesture.resetQuietTime();
3072 return false;
3073 }
3074
3075 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3076 return true;
3077 }
3078
3079 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3080 bool isQuietTime = false;
3081 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3082 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3083 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3084 currentFingerCount < 2) {
3085 // Enter quiet time when exiting swipe or freeform state.
3086 // This is to prevent accidentally entering the hover state and flinging the
3087 // pointer when finishing a swipe and there is still one pointer left onscreen.
3088 isQuietTime = true;
3089 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3090 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3091 // Enter quiet time when releasing the button and there are still two or more
3092 // fingers down. This may indicate that one finger was used to press the button
3093 // but it has not gone up yet.
3094 isQuietTime = true;
3095 }
3096 if (isQuietTime) {
3097 mPointerGesture.quietTime = when;
3098 }
3099 return isQuietTime;
3100}
3101
3102std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3103 int32_t bestId = -1;
3104 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3105 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3106 uint32_t id = idBits.clearFirstMarkedBit();
3107 std::optional<float> vx =
3108 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3109 std::optional<float> vy =
3110 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3111 if (vx && vy) {
3112 float speed = hypotf(*vx, *vy);
3113 if (speed > bestSpeed) {
3114 bestId = id;
3115 bestSpeed = speed;
3116 }
3117 }
3118 }
3119 return std::make_pair(bestId, bestSpeed);
3120}
3121
3122void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3123 bool* finishPreviousGesture) {
3124 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3125 // to move before deciding what to do.
3126 //
3127 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3128 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3129 // just a press or long-press at the pointer location.
3130 //
3131 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3132 // pointer location.
3133 //
3134 // When the two fingers move enough or when additional fingers are added, we make a decision to
3135 // transition into SWIPE or FREEFORM mode accordingly.
3136 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3137 ALOG_ASSERT(activeTouchId >= 0);
3138
3139 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3140 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3141 bool settled =
3142 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3143 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3144 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3145 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3146 *finishPreviousGesture = true;
3147 } else if (!settled && currentFingerCount > lastFingerCount) {
3148 // Additional pointers have gone down but not yet settled.
3149 // Reset the gesture.
3150 ALOGD_IF(DEBUG_GESTURES,
3151 "Gestures: Resetting gesture since additional pointers went down for "
3152 "MULTITOUCH, settle time remaining %0.3fms",
3153 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3154 when) * 0.000001f);
3155 *cancelPreviousGesture = true;
3156 } else {
3157 // Continue previous gesture.
3158 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3159 }
3160
3161 if (*finishPreviousGesture || *cancelPreviousGesture) {
3162 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3163 mPointerGesture.activeGestureId = 0;
3164 mPointerGesture.referenceIdBits.clear();
3165 mPointerVelocityControl.reset();
3166
3167 // Use the centroid and pointer location as the reference points for the gesture.
3168 ALOGD_IF(DEBUG_GESTURES,
3169 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3170 "%0.3fms",
3171 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3172 when) * 0.000001f);
3173 mCurrentRawState.rawPointerData
3174 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3175 &mPointerGesture.referenceTouchY);
3176 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3177 &mPointerGesture.referenceGestureY);
3178 }
3179
3180 // Clear the reference deltas for fingers not yet included in the reference calculation.
3181 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3182 ~mPointerGesture.referenceIdBits.value);
3183 !idBits.isEmpty();) {
3184 uint32_t id = idBits.clearFirstMarkedBit();
3185 mPointerGesture.referenceDeltas[id].dx = 0;
3186 mPointerGesture.referenceDeltas[id].dy = 0;
3187 }
3188 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3189
3190 // Add delta for all fingers and calculate a common movement delta.
3191 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3192 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3193 mCurrentCookedState.fingerIdBits.value);
3194 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3195 bool first = (idBits == commonIdBits);
3196 uint32_t id = idBits.clearFirstMarkedBit();
3197 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3198 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3199 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3200 delta.dx += cpd.x - lpd.x;
3201 delta.dy += cpd.y - lpd.y;
3202
3203 if (first) {
3204 commonDeltaRawX = delta.dx;
3205 commonDeltaRawY = delta.dy;
3206 } else {
3207 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3208 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3209 }
3210 }
3211
3212 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3213 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3214 float dist[MAX_POINTER_ID + 1];
3215 int32_t distOverThreshold = 0;
3216 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3217 uint32_t id = idBits.clearFirstMarkedBit();
3218 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3219 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3220 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3221 distOverThreshold += 1;
3222 }
3223 }
3224
3225 // Only transition when at least two pointers have moved further than
3226 // the minimum distance threshold.
3227 if (distOverThreshold >= 2) {
3228 if (currentFingerCount > 2) {
3229 // There are more than two pointers, switch to FREEFORM.
3230 ALOGD_IF(DEBUG_GESTURES,
3231 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3232 currentFingerCount);
3233 *cancelPreviousGesture = true;
3234 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3235 } else {
3236 // There are exactly two pointers.
3237 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3238 uint32_t id1 = idBits.clearFirstMarkedBit();
3239 uint32_t id2 = idBits.firstMarkedBit();
3240 const RawPointerData::Pointer& p1 =
3241 mCurrentRawState.rawPointerData.pointerForId(id1);
3242 const RawPointerData::Pointer& p2 =
3243 mCurrentRawState.rawPointerData.pointerForId(id2);
3244 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3245 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3246 // There are two pointers but they are too far apart for a SWIPE,
3247 // switch to FREEFORM.
3248 ALOGD_IF(DEBUG_GESTURES,
3249 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3250 mutualDistance, mPointerGestureMaxSwipeWidth);
3251 *cancelPreviousGesture = true;
3252 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3253 } else {
3254 // There are two pointers. Wait for both pointers to start moving
3255 // before deciding whether this is a SWIPE or FREEFORM gesture.
3256 float dist1 = dist[id1];
3257 float dist2 = dist[id2];
3258 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3259 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3260 // Calculate the dot product of the displacement vectors.
3261 // When the vectors are oriented in approximately the same direction,
3262 // the angle betweeen them is near zero and the cosine of the angle
3263 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3264 // mag(v2).
3265 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3266 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3267 float dx1 = delta1.dx * mPointerXZoomScale;
3268 float dy1 = delta1.dy * mPointerYZoomScale;
3269 float dx2 = delta2.dx * mPointerXZoomScale;
3270 float dy2 = delta2.dy * mPointerYZoomScale;
3271 float dot = dx1 * dx2 + dy1 * dy2;
3272 float cosine = dot / (dist1 * dist2); // denominator always > 0
3273 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3274 // Pointers are moving in the same direction. Switch to SWIPE.
3275 ALOGD_IF(DEBUG_GESTURES,
3276 "Gestures: PRESS transitioned to SWIPE, "
3277 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3278 "cosine %0.3f >= %0.3f",
3279 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3280 mConfig.pointerGestureMultitouchMinDistance, cosine,
3281 mConfig.pointerGestureSwipeTransitionAngleCosine);
3282 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3283 } else {
3284 // Pointers are moving in different directions. Switch to FREEFORM.
3285 ALOGD_IF(DEBUG_GESTURES,
3286 "Gestures: PRESS transitioned to FREEFORM, "
3287 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3288 "cosine %0.3f < %0.3f",
3289 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3290 mConfig.pointerGestureMultitouchMinDistance, cosine,
3291 mConfig.pointerGestureSwipeTransitionAngleCosine);
3292 *cancelPreviousGesture = true;
3293 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3294 }
3295 }
3296 }
3297 }
3298 }
3299 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3300 // Switch from SWIPE to FREEFORM if additional pointers go down.
3301 // Cancel previous gesture.
3302 if (currentFingerCount > 2) {
3303 ALOGD_IF(DEBUG_GESTURES,
3304 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3305 currentFingerCount);
3306 *cancelPreviousGesture = true;
3307 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3308 }
3309 }
3310
3311 // Move the reference points based on the overall group motion of the fingers
3312 // except in PRESS mode while waiting for a transition to occur.
3313 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3314 (commonDeltaRawX || commonDeltaRawY)) {
3315 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3316 uint32_t id = idBits.clearFirstMarkedBit();
3317 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3318 delta.dx = 0;
3319 delta.dy = 0;
3320 }
3321
3322 mPointerGesture.referenceTouchX += commonDeltaRawX;
3323 mPointerGesture.referenceTouchY += commonDeltaRawY;
3324
3325 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3326 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3327
3328 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3329 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3330
3331 mPointerGesture.referenceGestureX += commonDeltaX;
3332 mPointerGesture.referenceGestureY += commonDeltaY;
3333 }
3334
3335 // Report gestures.
3336 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3337 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3338 // PRESS or SWIPE mode.
3339 ALOGD_IF(DEBUG_GESTURES,
3340 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3341 "currentTouchPointerCount=%d",
3342 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3343 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3344
3345 mPointerGesture.currentGestureIdBits.clear();
3346 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3347 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3348 mPointerGesture.currentGestureProperties[0].clear();
3349 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3350 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3351 mPointerGesture.currentGestureCoords[0].clear();
3352 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3353 mPointerGesture.referenceGestureX);
3354 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3355 mPointerGesture.referenceGestureY);
3356 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3357 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3358 float xOffset = static_cast<float>(commonDeltaRawX) /
3359 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3360 float yOffset = static_cast<float>(commonDeltaRawY) /
3361 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3362 mPointerGesture.currentGestureCoords[0]
3363 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3364 mPointerGesture.currentGestureCoords[0]
3365 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3366 }
3367 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3368 // FREEFORM mode.
3369 ALOGD_IF(DEBUG_GESTURES,
3370 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3371 "currentTouchPointerCount=%d",
3372 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3373 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3374
3375 mPointerGesture.currentGestureIdBits.clear();
3376
3377 BitSet32 mappedTouchIdBits;
3378 BitSet32 usedGestureIdBits;
3379 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3380 // Initially, assign the active gesture id to the active touch point
3381 // if there is one. No other touch id bits are mapped yet.
3382 if (!*cancelPreviousGesture) {
3383 mappedTouchIdBits.markBit(activeTouchId);
3384 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3385 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3386 mPointerGesture.activeGestureId;
3387 } else {
3388 mPointerGesture.activeGestureId = -1;
3389 }
3390 } else {
3391 // Otherwise, assume we mapped all touches from the previous frame.
3392 // Reuse all mappings that are still applicable.
3393 mappedTouchIdBits.value =
3394 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3395 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3396
3397 // Check whether we need to choose a new active gesture id because the
3398 // current went went up.
3399 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3400 ~mCurrentCookedState.fingerIdBits.value);
3401 !upTouchIdBits.isEmpty();) {
3402 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3403 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3404 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3405 mPointerGesture.activeGestureId = -1;
3406 break;
3407 }
3408 }
3409 }
3410
3411 ALOGD_IF(DEBUG_GESTURES,
3412 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3413 "activeGestureId=%d",
3414 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3415
3416 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3417 for (uint32_t i = 0; i < currentFingerCount; i++) {
3418 uint32_t touchId = idBits.clearFirstMarkedBit();
3419 uint32_t gestureId;
3420 if (!mappedTouchIdBits.hasBit(touchId)) {
3421 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3422 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3423 ALOGD_IF(DEBUG_GESTURES,
3424 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3425 gestureId);
3426 } else {
3427 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3428 ALOGD_IF(DEBUG_GESTURES,
3429 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3430 touchId, gestureId);
3431 }
3432 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3433 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3434
3435 const RawPointerData::Pointer& pointer =
3436 mCurrentRawState.rawPointerData.pointerForId(touchId);
3437 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3438 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3439 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3440
3441 mPointerGesture.currentGestureProperties[i].clear();
3442 mPointerGesture.currentGestureProperties[i].id = gestureId;
3443 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3444 mPointerGesture.currentGestureCoords[i].clear();
3445 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3446 mPointerGesture.referenceGestureX +
3447 deltaX);
3448 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3449 mPointerGesture.referenceGestureY +
3450 deltaY);
3451 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3452 }
3453
3454 if (mPointerGesture.activeGestureId < 0) {
3455 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3456 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3457 mPointerGesture.activeGestureId);
3458 }
3459 }
3460}
3461
Harry Cutts714d1ad2022-08-24 16:36:43 +00003462void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3463 const RawPointerData::Pointer& currentPointer =
3464 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3465 const RawPointerData::Pointer& lastPointer =
3466 mLastRawState.rawPointerData.pointerForId(pointerId);
3467 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3468 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3469
3470 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3471 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3472
3473 mPointerController->move(deltaX, deltaY);
3474}
3475
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003476std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3477 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003478 mPointerSimple.currentCoords.clear();
3479 mPointerSimple.currentProperties.clear();
3480
3481 bool down, hovering;
3482 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3483 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3484 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003485 mPointerController
3486 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3487 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003488
3489 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3490 down = !hovering;
3491
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003492 float x, y;
3493 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003494 mPointerSimple.currentCoords.copyFrom(
3495 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3496 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3497 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3498 mPointerSimple.currentProperties.id = 0;
3499 mPointerSimple.currentProperties.toolType =
3500 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3501 } else {
3502 down = false;
3503 hovering = false;
3504 }
3505
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003506 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003507}
3508
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003509std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3510 uint32_t policyFlags) {
3511 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003512}
3513
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003514std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3515 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003516 mPointerSimple.currentCoords.clear();
3517 mPointerSimple.currentProperties.clear();
3518
3519 bool down, hovering;
3520 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3521 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003522 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003523 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003524 } else {
3525 mPointerVelocityControl.reset();
3526 }
3527
3528 down = isPointerDown(mCurrentRawState.buttonState);
3529 hovering = !down;
3530
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003531 float x, y;
3532 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003533 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003534 mPointerSimple.currentCoords.copyFrom(
3535 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3536 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3537 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3538 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3539 hovering ? 0.0f : 1.0f);
3540 mPointerSimple.currentProperties.id = 0;
3541 mPointerSimple.currentProperties.toolType =
3542 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3543 } else {
3544 mPointerVelocityControl.reset();
3545
3546 down = false;
3547 hovering = false;
3548 }
3549
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003550 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003551}
3552
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003553std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3554 uint32_t policyFlags) {
3555 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003556
3557 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003558
3559 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003560}
3561
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003562std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3563 uint32_t policyFlags, bool down,
3564 bool hovering) {
3565 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003566 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567
3568 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003569 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570 mPointerController->clearSpots();
3571 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003572 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003574 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003575 }
Garfield Tan9514d782020-11-10 16:37:23 -08003576 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003577
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003578 float xCursorPosition, yCursorPosition;
3579 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003580
3581 if (mPointerSimple.down && !down) {
3582 mPointerSimple.down = false;
3583
3584 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003585 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3586 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3587 0, metaState, mLastRawState.buttonState,
3588 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3589 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3590 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3591 yCursorPosition, mPointerSimple.downTime,
3592 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593 }
3594
3595 if (mPointerSimple.hovering && !hovering) {
3596 mPointerSimple.hovering = false;
3597
3598 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003599 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3600 mSource, displayId, policyFlags,
3601 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3602 mLastRawState.buttonState, MotionClassification::NONE,
3603 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3604 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3605 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3606 yCursorPosition, mPointerSimple.downTime,
3607 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003608 }
3609
3610 if (down) {
3611 if (!mPointerSimple.down) {
3612 mPointerSimple.down = true;
3613 mPointerSimple.downTime = when;
3614
3615 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003616 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3617 mSource, displayId, policyFlags,
3618 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3619 mCurrentRawState.buttonState, MotionClassification::NONE,
3620 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3621 &mPointerSimple.currentProperties,
3622 &mPointerSimple.currentCoords, mOrientedXPrecision,
3623 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3624 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003625 }
3626
3627 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003628 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3629 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3630 0, 0, metaState, mCurrentRawState.buttonState,
3631 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3632 &mPointerSimple.currentProperties,
3633 &mPointerSimple.currentCoords, mOrientedXPrecision,
3634 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3635 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003636 }
3637
3638 if (hovering) {
3639 if (!mPointerSimple.hovering) {
3640 mPointerSimple.hovering = true;
3641
3642 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003643 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3644 mSource, displayId, policyFlags,
3645 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3646 mCurrentRawState.buttonState, MotionClassification::NONE,
3647 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3648 &mPointerSimple.currentProperties,
3649 &mPointerSimple.currentCoords, mOrientedXPrecision,
3650 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3651 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003652 }
3653
3654 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003655 out.push_back(
3656 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3657 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3658 metaState, mCurrentRawState.buttonState,
3659 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3660 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3661 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3662 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003663 }
3664
3665 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3666 float vscroll = mCurrentRawState.rawVScroll;
3667 float hscroll = mCurrentRawState.rawHScroll;
3668 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3669 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3670
3671 // Send scroll.
3672 PointerCoords pointerCoords;
3673 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3674 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3675 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3676
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003677 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3678 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3679 0, 0, metaState, mCurrentRawState.buttonState,
3680 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3681 &mPointerSimple.currentProperties, &pointerCoords,
3682 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3683 yCursorPosition, mPointerSimple.downTime,
3684 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003685 }
3686
3687 // Save state.
3688 if (down || hovering) {
3689 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3690 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3691 } else {
3692 mPointerSimple.reset();
3693 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003694 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003695}
3696
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003697std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3698 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003699 mPointerSimple.currentCoords.clear();
3700 mPointerSimple.currentProperties.clear();
3701
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003702 return dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003703}
3704
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003705NotifyMotionArgs TouchInputMapper::dispatchMotion(
3706 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3707 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003708 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3709 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003710 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003711 PointerCoords pointerCoords[MAX_POINTERS];
3712 PointerProperties pointerProperties[MAX_POINTERS];
3713 uint32_t pointerCount = 0;
3714 while (!idBits.isEmpty()) {
3715 uint32_t id = idBits.clearFirstMarkedBit();
3716 uint32_t index = idToIndex[id];
3717 pointerProperties[pointerCount].copyFrom(properties[index]);
3718 pointerCoords[pointerCount].copyFrom(coords[index]);
3719
3720 if (changedId >= 0 && id == uint32_t(changedId)) {
3721 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3722 }
3723
3724 pointerCount += 1;
3725 }
3726
3727 ALOG_ASSERT(pointerCount != 0);
3728
3729 if (changedId >= 0 && pointerCount == 1) {
3730 // Replace initial down and final up action.
3731 // We can compare the action without masking off the changed pointer index
3732 // because we know the index is 0.
3733 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3734 action = AMOTION_EVENT_ACTION_DOWN;
3735 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003736 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3737 action = AMOTION_EVENT_ACTION_CANCEL;
3738 } else {
3739 action = AMOTION_EVENT_ACTION_UP;
3740 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003741 } else {
3742 // Can't happen.
3743 ALOG_ASSERT(false);
3744 }
3745 }
3746 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3747 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003748 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003749 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003750 }
3751 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3752 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003753 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003754 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003755 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003756 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3757 policyFlags, action, actionButton, flags, metaState, buttonState,
3758 classification, edgeFlags, pointerCount, pointerProperties,
3759 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3760 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003761}
3762
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003763std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3764 std::list<NotifyArgs> out;
3765 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3766 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3767 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003768}
3769
Prabir Pradhan1728b212021-10-19 16:00:03 -07003770// Transform input device coordinates to display panel coordinates.
3771void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003772 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3773 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3774
arthurhunga36b28e2020-12-29 20:28:15 +08003775 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3776 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3777
Prabir Pradhan1728b212021-10-19 16:00:03 -07003778 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003779 // 0 - no swap and reverse.
3780 // 90 - swap x/y and reverse y.
3781 // 180 - reverse x, y.
3782 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003783 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003784 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003785 x = xScaled;
3786 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003787 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003788 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003789 y = xScaledMax;
3790 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003791 break;
3792 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003793 x = xScaledMax;
3794 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003795 break;
3796 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003797 y = xScaled;
3798 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003799 break;
3800 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003801 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003802 }
3803}
3804
Prabir Pradhan1728b212021-10-19 16:00:03 -07003805bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003806 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3807 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3808
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003809 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003810 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003811 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003812 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003813}
3814
3815const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3816 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003817 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3818 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3819 "left=%d, top=%d, right=%d, bottom=%d",
3820 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3821 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003822
3823 if (virtualKey.isHit(x, y)) {
3824 return &virtualKey;
3825 }
3826 }
3827
3828 return nullptr;
3829}
3830
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003831void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3832 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3833 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003834
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003835 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003836
3837 if (currentPointerCount == 0) {
3838 // No pointers to assign.
3839 return;
3840 }
3841
3842 if (lastPointerCount == 0) {
3843 // All pointers are new.
3844 for (uint32_t i = 0; i < currentPointerCount; i++) {
3845 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003846 current.rawPointerData.pointers[i].id = id;
3847 current.rawPointerData.idToIndex[id] = i;
3848 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003849 }
3850 return;
3851 }
3852
3853 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003854 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003855 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003856 uint32_t id = last.rawPointerData.pointers[0].id;
3857 current.rawPointerData.pointers[0].id = id;
3858 current.rawPointerData.idToIndex[id] = 0;
3859 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003860 return;
3861 }
3862
3863 // General case.
3864 // We build a heap of squared euclidean distances between current and last pointers
3865 // associated with the current and last pointer indices. Then, we find the best
3866 // match (by distance) for each current pointer.
3867 // The pointers must have the same tool type but it is possible for them to
3868 // transition from hovering to touching or vice-versa while retaining the same id.
3869 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3870
3871 uint32_t heapSize = 0;
3872 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3873 currentPointerIndex++) {
3874 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3875 lastPointerIndex++) {
3876 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003877 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003878 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003879 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003880 if (currentPointer.toolType == lastPointer.toolType) {
3881 int64_t deltaX = currentPointer.x - lastPointer.x;
3882 int64_t deltaY = currentPointer.y - lastPointer.y;
3883
3884 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3885
3886 // Insert new element into the heap (sift up).
3887 heap[heapSize].currentPointerIndex = currentPointerIndex;
3888 heap[heapSize].lastPointerIndex = lastPointerIndex;
3889 heap[heapSize].distance = distance;
3890 heapSize += 1;
3891 }
3892 }
3893 }
3894
3895 // Heapify
3896 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3897 startIndex -= 1;
3898 for (uint32_t parentIndex = startIndex;;) {
3899 uint32_t childIndex = parentIndex * 2 + 1;
3900 if (childIndex >= heapSize) {
3901 break;
3902 }
3903
3904 if (childIndex + 1 < heapSize &&
3905 heap[childIndex + 1].distance < heap[childIndex].distance) {
3906 childIndex += 1;
3907 }
3908
3909 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3910 break;
3911 }
3912
3913 swap(heap[parentIndex], heap[childIndex]);
3914 parentIndex = childIndex;
3915 }
3916 }
3917
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003918 if (DEBUG_POINTER_ASSIGNMENT) {
3919 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3920 for (size_t i = 0; i < heapSize; i++) {
3921 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3922 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3923 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003924 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003925
3926 // Pull matches out by increasing order of distance.
3927 // To avoid reassigning pointers that have already been matched, the loop keeps track
3928 // of which last and current pointers have been matched using the matchedXXXBits variables.
3929 // It also tracks the used pointer id bits.
3930 BitSet32 matchedLastBits(0);
3931 BitSet32 matchedCurrentBits(0);
3932 BitSet32 usedIdBits(0);
3933 bool first = true;
3934 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3935 while (heapSize > 0) {
3936 if (first) {
3937 // The first time through the loop, we just consume the root element of
3938 // the heap (the one with smallest distance).
3939 first = false;
3940 } else {
3941 // Previous iterations consumed the root element of the heap.
3942 // Pop root element off of the heap (sift down).
3943 heap[0] = heap[heapSize];
3944 for (uint32_t parentIndex = 0;;) {
3945 uint32_t childIndex = parentIndex * 2 + 1;
3946 if (childIndex >= heapSize) {
3947 break;
3948 }
3949
3950 if (childIndex + 1 < heapSize &&
3951 heap[childIndex + 1].distance < heap[childIndex].distance) {
3952 childIndex += 1;
3953 }
3954
3955 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3956 break;
3957 }
3958
3959 swap(heap[parentIndex], heap[childIndex]);
3960 parentIndex = childIndex;
3961 }
3962
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003963 if (DEBUG_POINTER_ASSIGNMENT) {
3964 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3965 for (size_t j = 0; j < heapSize; j++) {
3966 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3967 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3968 heap[j].distance);
3969 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003970 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003971 }
3972
3973 heapSize -= 1;
3974
3975 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3976 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3977
3978 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3979 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3980
3981 matchedCurrentBits.markBit(currentPointerIndex);
3982 matchedLastBits.markBit(lastPointerIndex);
3983
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003984 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3985 current.rawPointerData.pointers[currentPointerIndex].id = id;
3986 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3987 current.rawPointerData.markIdBit(id,
3988 current.rawPointerData.isHovering(
3989 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003990 usedIdBits.markBit(id);
3991
Harry Cutts45483602022-08-24 14:36:48 +00003992 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3993 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3994 ", distance=%" PRIu64,
3995 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003996 break;
3997 }
3998 }
3999
4000 // Assign fresh ids to pointers that were not matched in the process.
4001 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4002 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4003 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4004
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004005 current.rawPointerData.pointers[currentPointerIndex].id = id;
4006 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4007 current.rawPointerData.markIdBit(id,
4008 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004009
Harry Cutts45483602022-08-24 14:36:48 +00004010 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4011 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4012 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004013 }
4014}
4015
4016int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4017 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4018 return AKEY_STATE_VIRTUAL;
4019 }
4020
4021 for (const VirtualKey& virtualKey : mVirtualKeys) {
4022 if (virtualKey.keyCode == keyCode) {
4023 return AKEY_STATE_UP;
4024 }
4025 }
4026
4027 return AKEY_STATE_UNKNOWN;
4028}
4029
4030int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4031 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4032 return AKEY_STATE_VIRTUAL;
4033 }
4034
4035 for (const VirtualKey& virtualKey : mVirtualKeys) {
4036 if (virtualKey.scanCode == scanCode) {
4037 return AKEY_STATE_UP;
4038 }
4039 }
4040
4041 return AKEY_STATE_UNKNOWN;
4042}
4043
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004044bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4045 const std::vector<int32_t>& keyCodes,
4046 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004047 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004048 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004049 if (virtualKey.keyCode == keyCodes[i]) {
4050 outFlags[i] = 1;
4051 }
4052 }
4053 }
4054
4055 return true;
4056}
4057
4058std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4059 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004060 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004061 return std::make_optional(mPointerController->getDisplayId());
4062 } else {
4063 return std::make_optional(mViewport.displayId);
4064 }
4065 }
4066 return std::nullopt;
4067}
4068
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004069} // namespace android