blob: bf73ce5db8bbc9fc19ac24e7fe047d179eabfa9c [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
24
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070025#include "CursorButtonAccumulator.h"
26#include "CursorScrollAccumulator.h"
27#include "TouchButtonAccumulator.h"
28#include "TouchCursorInputMapperCommon.h"
29
30namespace android {
31
32// --- Constants ---
33
34// Maximum amount of latency to add to touch events while waiting for data from an
35// external stylus.
36static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
37
38// Maximum amount of time to wait on touch data before pushing out new pressure data.
39static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
40
41// Artificial latency on synthetic events created from stylus data without corresponding touch
42// data.
43static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
44
HQ Liue6983c72022-04-19 22:14:56 +000045// Minimum width between two pointers to determine a gesture as freeform gesture in mm
46static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070047// --- Static Definitions ---
48
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000049static const DisplayViewport kUninitializedViewport;
50
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070051template <typename T>
52inline static void swap(T& a, T& b) {
53 T temp = a;
54 a = b;
55 b = temp;
56}
57
58static float calculateCommonVector(float a, float b) {
59 if (a > 0 && b > 0) {
60 return a < b ? a : b;
61 } else if (a < 0 && b < 0) {
62 return a > b ? a : b;
63 } else {
64 return 0;
65 }
66}
67
68inline static float distance(float x1, float y1, float x2, float y2) {
69 return hypotf(x1 - x2, y1 - y2);
70}
71
72inline static int32_t signExtendNybble(int32_t value) {
73 return value >= 8 ? value - 16 : value;
74}
75
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070076// --- RawPointerData ---
77
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070078void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
79 float x = 0, y = 0;
80 uint32_t count = touchingIdBits.count();
81 if (count) {
82 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
83 uint32_t id = idBits.clearFirstMarkedBit();
84 const Pointer& pointer = pointerForId(id);
85 x += pointer.x;
86 y += pointer.y;
87 }
88 x /= count;
89 y /= count;
90 }
91 *outX = x;
92 *outY = y;
93}
94
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070095// --- TouchInputMapper ---
96
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -080097TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
98 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +000099 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700100 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100101 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700102 mDisplayWidth(-1),
103 mDisplayHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700104 mPhysicalWidth(-1),
105 mPhysicalHeight(-1),
106 mPhysicalLeft(0),
107 mPhysicalTop(0),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700108 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109
110TouchInputMapper::~TouchInputMapper() {}
111
Philip Junker4af3b3d2021-12-14 10:36:55 +0100112uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700113 return mSource;
114}
115
116void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
117 InputMapper::populateDeviceInfo(info);
118
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000119 if (mDeviceMode == DeviceMode::DISABLED) {
120 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700121 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000122
123 info->addMotionRange(mOrientedRanges.x);
124 info->addMotionRange(mOrientedRanges.y);
125 info->addMotionRange(mOrientedRanges.pressure);
126
127 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
128 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
129 //
130 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
131 // motion, i.e. the hardware dimensions, as the finger could move completely across the
132 // touchpad in one sample cycle.
133 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
134 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
135 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
136 x.resolution);
137 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
138 y.resolution);
139 }
140
141 if (mOrientedRanges.size) {
142 info->addMotionRange(*mOrientedRanges.size);
143 }
144
145 if (mOrientedRanges.touchMajor) {
146 info->addMotionRange(*mOrientedRanges.touchMajor);
147 info->addMotionRange(*mOrientedRanges.touchMinor);
148 }
149
150 if (mOrientedRanges.toolMajor) {
151 info->addMotionRange(*mOrientedRanges.toolMajor);
152 info->addMotionRange(*mOrientedRanges.toolMinor);
153 }
154
155 if (mOrientedRanges.orientation) {
156 info->addMotionRange(*mOrientedRanges.orientation);
157 }
158
159 if (mOrientedRanges.distance) {
160 info->addMotionRange(*mOrientedRanges.distance);
161 }
162
163 if (mOrientedRanges.tilt) {
164 info->addMotionRange(*mOrientedRanges.tilt);
165 }
166
167 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
168 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
169 }
170 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
171 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
172 }
173 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
174 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
175 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
176 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
177 x.resolution);
178 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
179 y.resolution);
180 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
181 x.resolution);
182 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
183 y.resolution);
184 }
185 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000186 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700187}
188
189void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700190 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800191 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192 dumpParameters(dump);
193 dumpVirtualKeys(dump);
194 dumpRawPointerAxes(dump);
195 dumpCalibration(dump);
196 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700197 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700198
199 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700200 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
201 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
202 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
203 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
204 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
205 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
206 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
207 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
208 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
209 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
210 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
211 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
212 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
213 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
214
215 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
216 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
217 mLastRawState.rawPointerData.pointerCount);
218 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
219 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
220 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
221 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
222 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
223 "toolType=%d, isHovering=%s\n",
224 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
225 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
226 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
227 pointer.distance, pointer.toolType, toString(pointer.isHovering));
228 }
229
230 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
231 mLastCookedState.buttonState);
232 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
233 mLastCookedState.cookedPointerData.pointerCount);
234 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
235 const PointerProperties& pointerProperties =
236 mLastCookedState.cookedPointerData.pointerProperties[i];
237 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000238 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
239 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
240 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700241 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
242 "toolType=%d, isHovering=%s\n",
243 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000244 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
245 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700246 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
247 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
248 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
249 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
250 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
251 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
252 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
253 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
254 pointerProperties.toolType,
255 toString(mLastCookedState.cookedPointerData.isHovering(i)));
256 }
257
258 dump += INDENT3 "Stylus Fusion:\n";
259 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
260 toString(mExternalStylusConnected));
261 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
262 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
263 mExternalStylusFusionTimeout);
264 dump += INDENT3 "External Stylus State:\n";
265 dumpStylusState(dump, mExternalStylusState);
266
Michael Wright227c5542020-07-02 18:30:52 +0100267 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700268 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
269 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
270 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
271 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
272 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
273 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
274 }
275}
276
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700277std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
278 const InputReaderConfiguration* config,
279 uint32_t changes) {
280 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700281
282 mConfig = *config;
283
284 if (!changes) { // first time only
285 // Configure basic parameters.
286 configureParameters();
287
288 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800289 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000290 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700291
292 // Configure absolute axis information.
293 configureRawPointerAxes();
294
295 // Prepare input device calibration.
296 parseCalibration();
297 resolveCalibration();
298 }
299
300 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
301 // Update location calibration to reflect current settings
302 updateAffineTransformation();
303 }
304
305 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
306 // Update pointer speed.
307 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
308 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
309 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
310 }
311
312 bool resetNeeded = false;
313 if (!changes ||
314 (changes &
315 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800316 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700317 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
318 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
319 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700320 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700321 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700322 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700323 }
324
325 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700326 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000327
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700328 // Send reset, unless this is the first time the device has been configured,
329 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000330 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700331 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700332 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333}
334
335void TouchInputMapper::resolveExternalStylusPresence() {
336 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800337 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700338 mExternalStylusConnected = !devices.empty();
339
340 if (!mExternalStylusConnected) {
341 resetExternalStylus();
342 }
343}
344
345void TouchInputMapper::configureParameters() {
346 // Use the pointer presentation mode for devices that do not support distinct
347 // multitouch. The spot-based presentation relies on being able to accurately
348 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800349 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100350 ? Parameters::GestureMode::SINGLE_TOUCH
351 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700352
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700353 std::string gestureModeString;
354 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800355 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700356 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100357 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700358 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100359 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700360 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700361 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700362 }
363 }
364
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800365 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700366 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100367 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800368 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700369 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100370 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700371 } else {
372 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100373 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374 }
375
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800376 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700377
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700378 std::string deviceTypeString;
379 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800380 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700381 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100382 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700383 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100384 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700385 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100386 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700387 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700388 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 }
390 }
391
Michael Wright227c5542020-07-02 18:30:52 +0100392 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700393 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800394 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700395
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700396 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700397 std::string orientationString;
398 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700399 orientationString)) {
400 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
401 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
402 } else if (orientationString == "ORIENTATION_90") {
403 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
404 } else if (orientationString == "ORIENTATION_180") {
405 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
406 } else if (orientationString == "ORIENTATION_270") {
407 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
408 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700409 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700410 }
411 }
412
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700413 mParameters.hasAssociatedDisplay = false;
414 mParameters.associatedDisplayIsExternal = false;
415 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100416 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
417 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700418 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100419 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800420 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700421 std::string uniqueDisplayId;
422 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800423 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700424 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
425 }
426 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800427 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 mParameters.hasAssociatedDisplay = true;
429 }
430
431 // Initial downs on external touch devices should wake the device.
432 // Normally we don't do this for internal touch screens to prevent them from waking
433 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800434 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700435 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000436
437 mParameters.supportsUsi = false;
438 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
439 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700440
441 mParameters.enableForInactiveViewport = false;
442 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
443 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444}
445
446void TouchInputMapper::dumpParameters(std::string& dump) {
447 dump += INDENT3 "Parameters:\n";
448
Dominik Laskowski75788452021-02-09 18:51:25 -0800449 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450
Dominik Laskowski75788452021-02-09 18:51:25 -0800451 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452
453 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
454 "displayId='%s'\n",
455 toString(mParameters.hasAssociatedDisplay),
456 toString(mParameters.associatedDisplayIsExternal),
457 mParameters.uniqueDisplayId.c_str());
458 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800459 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000460 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700461 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
462 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463}
464
465void TouchInputMapper::configureRawPointerAxes() {
466 mRawPointerAxes.clear();
467}
468
469void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
470 dump += INDENT3 "Raw Touch Axes:\n";
471 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
472 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
473 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
474 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
475 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
476 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
477 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
478 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
479 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
480 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
481 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
482 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
483 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
484}
485
486bool TouchInputMapper::hasExternalStylus() const {
487 return mExternalStylusConnected;
488}
489
490/**
491 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000492 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800493 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000494 * 3. Get the matching viewport by either unique id in idc file or by the display type
495 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800496 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700497 */
498std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800499 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000500 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800501 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502 }
503
Christine Franks2a2293c2022-01-18 11:51:16 -0800504 const std::optional<std::string> associatedDisplayUniqueId =
505 getDeviceContext().getAssociatedDisplayUniqueId();
506 if (associatedDisplayUniqueId) {
507 return getDeviceContext().getAssociatedViewport();
508 }
509
Michael Wright227c5542020-07-02 18:30:52 +0100510 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800511 std::optional<DisplayViewport> viewport =
512 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
513 if (viewport) {
514 return viewport;
515 } else {
516 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
517 mConfig.defaultPointerDisplayId);
518 }
519 }
520
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700521 // Check if uniqueDisplayId is specified in idc file.
522 if (!mParameters.uniqueDisplayId.empty()) {
523 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
524 }
525
526 ViewportType viewportTypeToUse;
527 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100528 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700529 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100530 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700531 }
532
533 std::optional<DisplayViewport> viewport =
534 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100535 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700536 ALOGW("Input device %s should be associated with external display, "
537 "fallback to internal one for the external viewport is not found.",
538 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100539 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700540 }
541
542 return viewport;
543 }
544
545 // No associated display, return a non-display viewport.
546 DisplayViewport newViewport;
547 // Raw width and height in the natural orientation.
548 int32_t rawWidth = mRawPointerAxes.getRawWidth();
549 int32_t rawHeight = mRawPointerAxes.getRawHeight();
550 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
551 return std::make_optional(newViewport);
552}
553
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800554int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
555 if (resolution < 0) {
556 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
557 getDeviceName().c_str());
558 return 0;
559 }
560 return resolution;
561}
562
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800563void TouchInputMapper::initializeSizeRanges() {
564 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
565 mSizeScale = 0.0f;
566 return;
567 }
568
569 // Size of diagonal axis.
570 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
571
572 // Size factors.
573 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
574 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
575 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
576 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
577 } else {
578 mSizeScale = 0.0f;
579 }
580
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700581 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
582 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
583 .source = mSource,
584 .min = 0,
585 .max = diagonalSize,
586 .flat = 0,
587 .fuzz = 0,
588 .resolution = 0,
589 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800590
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800591 if (mRawPointerAxes.touchMajor.valid) {
592 mRawPointerAxes.touchMajor.resolution =
593 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700594 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800595 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800596
597 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700598 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800599 if (mRawPointerAxes.touchMinor.valid) {
600 mRawPointerAxes.touchMinor.resolution =
601 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700602 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800603 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800604
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700605 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
606 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
607 .source = mSource,
608 .min = 0,
609 .max = diagonalSize,
610 .flat = 0,
611 .fuzz = 0,
612 .resolution = 0,
613 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800614 if (mRawPointerAxes.toolMajor.valid) {
615 mRawPointerAxes.toolMajor.resolution =
616 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700617 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800618 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800619
620 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700621 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800622 if (mRawPointerAxes.toolMinor.valid) {
623 mRawPointerAxes.toolMinor.resolution =
624 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700625 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800626 }
627
628 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700629 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
630 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
631 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
632 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800633 } else {
634 // Support for other calibrations can be added here.
635 ALOGW("%s calibration is not supported for size ranges at the moment. "
636 "Using raw resolution instead",
637 ftl::enum_string(mCalibration.sizeCalibration).c_str());
638 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800639
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700640 mOrientedRanges.size = InputDeviceInfo::MotionRange{
641 .axis = AMOTION_EVENT_AXIS_SIZE,
642 .source = mSource,
643 .min = 0,
644 .max = 1.0,
645 .flat = 0,
646 .fuzz = 0,
647 .resolution = 0,
648 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800649}
650
651void TouchInputMapper::initializeOrientedRanges() {
652 // Configure X and Y factors.
653 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
654 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
655 mXPrecision = 1.0f / mXScale;
656 mYPrecision = 1.0f / mYScale;
657
658 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
659 mOrientedRanges.x.source = mSource;
660 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
661 mOrientedRanges.y.source = mSource;
662
663 // Scale factor for terms that are not oriented in a particular axis.
664 // If the pixels are square then xScale == yScale otherwise we fake it
665 // by choosing an average.
666 mGeometricScale = avg(mXScale, mYScale);
667
668 initializeSizeRanges();
669
670 // Pressure factors.
671 mPressureScale = 0;
672 float pressureMax = 1.0;
673 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
674 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700675 if (mCalibration.pressureScale) {
676 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800677 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
678 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
679 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
680 }
681 }
682
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700683 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
684 .axis = AMOTION_EVENT_AXIS_PRESSURE,
685 .source = mSource,
686 .min = 0,
687 .max = pressureMax,
688 .flat = 0,
689 .fuzz = 0,
690 .resolution = 0,
691 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800692
693 // Tilt
694 mTiltXCenter = 0;
695 mTiltXScale = 0;
696 mTiltYCenter = 0;
697 mTiltYScale = 0;
698 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
699 if (mHaveTilt) {
700 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
701 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
702 mTiltXScale = M_PI / 180;
703 mTiltYScale = M_PI / 180;
704
705 if (mRawPointerAxes.tiltX.resolution) {
706 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
707 }
708 if (mRawPointerAxes.tiltY.resolution) {
709 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
710 }
711
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700712 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
713 .axis = AMOTION_EVENT_AXIS_TILT,
714 .source = mSource,
715 .min = 0,
716 .max = M_PI_2,
717 .flat = 0,
718 .fuzz = 0,
719 .resolution = 0,
720 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800721 }
722
723 // Orientation
724 mOrientationScale = 0;
725 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700726 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
727 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
728 .source = mSource,
729 .min = -M_PI,
730 .max = M_PI,
731 .flat = 0,
732 .fuzz = 0,
733 .resolution = 0,
734 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800735
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800736 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
737 if (mCalibration.orientationCalibration ==
738 Calibration::OrientationCalibration::INTERPOLATED) {
739 if (mRawPointerAxes.orientation.valid) {
740 if (mRawPointerAxes.orientation.maxValue > 0) {
741 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
742 } else if (mRawPointerAxes.orientation.minValue < 0) {
743 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
744 } else {
745 mOrientationScale = 0;
746 }
747 }
748 }
749
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700750 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
751 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
752 .source = mSource,
753 .min = -M_PI_2,
754 .max = M_PI_2,
755 .flat = 0,
756 .fuzz = 0,
757 .resolution = 0,
758 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800759 }
760
761 // Distance
762 mDistanceScale = 0;
763 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
764 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700765 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800766 }
767
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700768 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800769
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700770 .axis = AMOTION_EVENT_AXIS_DISTANCE,
771 .source = mSource,
772 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
773 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
774 .flat = 0,
775 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
776 .resolution = 0,
777 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800778 }
779
780 // Compute oriented precision, scales and ranges.
781 // Note that the maximum value reported is an inclusive maximum value so it is one
782 // unit less than the total width or height of the display.
783 switch (mInputDeviceOrientation) {
784 case DISPLAY_ORIENTATION_90:
785 case DISPLAY_ORIENTATION_270:
786 mOrientedXPrecision = mYPrecision;
787 mOrientedYPrecision = mXPrecision;
788
789 mOrientedRanges.x.min = 0;
790 mOrientedRanges.x.max = mDisplayHeight - 1;
791 mOrientedRanges.x.flat = 0;
792 mOrientedRanges.x.fuzz = 0;
793 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
794
795 mOrientedRanges.y.min = 0;
796 mOrientedRanges.y.max = mDisplayWidth - 1;
797 mOrientedRanges.y.flat = 0;
798 mOrientedRanges.y.fuzz = 0;
799 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
800 break;
801
802 default:
803 mOrientedXPrecision = mXPrecision;
804 mOrientedYPrecision = mYPrecision;
805
806 mOrientedRanges.x.min = 0;
807 mOrientedRanges.x.max = mDisplayWidth - 1;
808 mOrientedRanges.x.flat = 0;
809 mOrientedRanges.x.fuzz = 0;
810 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
811
812 mOrientedRanges.y.min = 0;
813 mOrientedRanges.y.max = mDisplayHeight - 1;
814 mOrientedRanges.y.flat = 0;
815 mOrientedRanges.y.fuzz = 0;
816 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
817 break;
818 }
819}
820
Prabir Pradhan1728b212021-10-19 16:00:03 -0700821void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000822 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700823
824 resolveExternalStylusPresence();
825
826 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100827 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000828 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700829 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100830 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700831 if (hasStylus()) {
832 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000833 } else {
834 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700835 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800836 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700837 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100838 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700839 if (hasStylus()) {
840 mSource |= AINPUT_SOURCE_STYLUS;
841 }
842 if (hasExternalStylus()) {
843 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
844 }
Michael Wright227c5542020-07-02 18:30:52 +0100845 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700846 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100847 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700848 } else {
849 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100850 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700851 }
852
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000853 const std::optional<DisplayViewport> newViewportOpt = findViewport();
854
855 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700856 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
857 ALOGW("Touch device '%s' did not report support for X or Y axis! "
858 "The device will be inoperable.",
859 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100860 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000861 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700862 ALOGI("Touch device '%s' could not query the properties of its associated "
863 "display. The device will be inoperable until the display size "
864 "becomes available.",
865 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100866 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700867 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000868 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
869 getDeviceName().c_str(), getDeviceId());
870 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000871 }
872
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700873 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700874 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
875 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000876 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
877 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
878 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
879 const float rawMeanResolution =
880 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700881
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000882 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
883 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700884 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700885 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000886 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
887 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
888 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700889
Michael Wright227c5542020-07-02 18:30:52 +0100890 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700891 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700892 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
893 int32_t naturalPhysicalLeft, naturalPhysicalTop;
894 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700895
Prabir Pradhan1728b212021-10-19 16:00:03 -0700896 // Apply the inverse of the input device orientation so that the input device is
897 // configured in the same orientation as the viewport. The input device orientation will
898 // be re-applied by mInputDeviceOrientation.
899 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700900 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700901 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
904 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800905 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700906 naturalPhysicalTop = mViewport.physicalLeft;
907 naturalDeviceWidth = mViewport.deviceHeight;
908 naturalDeviceHeight = mViewport.deviceWidth;
909 break;
910 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
912 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
913 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
914 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
915 naturalDeviceWidth = mViewport.deviceWidth;
916 naturalDeviceHeight = mViewport.deviceHeight;
917 break;
918 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700919 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
920 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
921 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800922 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700923 naturalDeviceWidth = mViewport.deviceHeight;
924 naturalDeviceHeight = mViewport.deviceWidth;
925 break;
926 case DISPLAY_ORIENTATION_0:
927 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700928 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
929 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
930 naturalPhysicalLeft = mViewport.physicalLeft;
931 naturalPhysicalTop = mViewport.physicalTop;
932 naturalDeviceWidth = mViewport.deviceWidth;
933 naturalDeviceHeight = mViewport.deviceHeight;
934 break;
935 }
936
937 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
938 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
939 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
940 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
941 }
942
943 mPhysicalWidth = naturalPhysicalWidth;
944 mPhysicalHeight = naturalPhysicalHeight;
945 mPhysicalLeft = naturalPhysicalLeft;
946 mPhysicalTop = naturalPhysicalTop;
947
Prabir Pradhan1728b212021-10-19 16:00:03 -0700948 const int32_t oldDisplayWidth = mDisplayWidth;
949 const int32_t oldDisplayHeight = mDisplayHeight;
950 mDisplayWidth = naturalDeviceWidth;
951 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700952
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000953 // InputReader works in the un-rotated display coordinate space, so we don't need to do
954 // anything if the device is already orientation-aware. If the device is not
955 // orientation-aware, then we need to apply the inverse rotation of the display so that
956 // when the display rotation is applied later as a part of the per-window transform, we
957 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700958 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000959 ? DISPLAY_ORIENTATION_0
960 : getInverseRotation(mViewport.orientation);
961 // For orientation-aware devices that work in the un-rotated coordinate space, the
962 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000963 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
964 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
965 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700966
967 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700968 mInputDeviceOrientation =
969 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700970 } else {
971 mPhysicalWidth = rawWidth;
972 mPhysicalHeight = rawHeight;
973 mPhysicalLeft = 0;
974 mPhysicalTop = 0;
975
Prabir Pradhan1728b212021-10-19 16:00:03 -0700976 mDisplayWidth = rawWidth;
977 mDisplayHeight = rawHeight;
978 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700979 }
980 }
981
982 // If moving between pointer modes, need to reset some state.
983 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
984 if (deviceModeChanged) {
985 mOrientedRanges.clear();
986 }
987
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800988 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
989 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100990 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800991 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000992 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
993 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800994 if (mPointerController == nullptr) {
995 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000997 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800998 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
999 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001000 } else {
lilinnandef700b2022-06-17 19:32:01 +08001001 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1002 !mConfig.showTouches) {
1003 mPointerController->clearSpots();
1004 }
Michael Wright17db18e2020-06-26 20:51:44 +01001005 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001006 }
1007
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001008 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001009 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1010 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001011 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1012 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001013
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001014 configureVirtualKeys();
1015
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001016 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001017
1018 // Location
1019 updateAffineTransformation();
1020
Michael Wright227c5542020-07-02 18:30:52 +01001021 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001022 // Compute pointer gesture detection parameters.
1023 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001024 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001025
1026 // Scale movements such that one whole swipe of the touch pad covers a
1027 // given area relative to the diagonal size of the display when no acceleration
1028 // is applied.
1029 // Assume that the touch pad has a square aspect ratio such that movements in
1030 // X and Y of the same number of raw units cover the same physical distance.
1031 mPointerXMovementScale =
1032 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1033 mPointerYMovementScale = mPointerXMovementScale;
1034
1035 // Scale zooms to cover a smaller range of the display than movements do.
1036 // This value determines the area around the pointer that is affected by freeform
1037 // pointer gestures.
1038 mPointerXZoomScale =
1039 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1040 mPointerYZoomScale = mPointerXZoomScale;
1041
HQ Liue6983c72022-04-19 22:14:56 +00001042 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1043 // axis is non positive value.
1044 const float minFreeformGestureWidth =
1045 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1046
1047 mPointerGestureMaxSwipeWidth =
1048 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1049 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001050 }
1051
1052 // Inform the dispatcher about the changes.
1053 *outResetNeeded = true;
1054 bumpGeneration();
1055 }
1056}
1057
Prabir Pradhan1728b212021-10-19 16:00:03 -07001058void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001060 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1061 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1063 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1064 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1065 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001066 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067}
1068
1069void TouchInputMapper::configureVirtualKeys() {
1070 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001071 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001072
1073 mVirtualKeys.clear();
1074
1075 if (virtualKeyDefinitions.size() == 0) {
1076 return;
1077 }
1078
1079 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1080 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1081 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1082 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1083
1084 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1085 VirtualKey virtualKey;
1086
1087 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1088 int32_t keyCode;
1089 int32_t dummyKeyMetaState;
1090 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001091 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1092 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001093 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1094 continue; // drop the key
1095 }
1096
1097 virtualKey.keyCode = keyCode;
1098 virtualKey.flags = flags;
1099
1100 // convert the key definition's display coordinates into touch coordinates for a hit box
1101 int32_t halfWidth = virtualKeyDefinition.width / 2;
1102 int32_t halfHeight = virtualKeyDefinition.height / 2;
1103
1104 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001105 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001106 touchScreenLeft;
1107 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001108 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001110 virtualKey.hitTop =
1111 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001113 virtualKey.hitBottom =
1114 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001115 touchScreenTop;
1116 mVirtualKeys.push_back(virtualKey);
1117 }
1118}
1119
1120void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1121 if (!mVirtualKeys.empty()) {
1122 dump += INDENT3 "Virtual Keys:\n";
1123
1124 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1125 const VirtualKey& virtualKey = mVirtualKeys[i];
1126 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1127 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1128 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1129 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1130 }
1131 }
1132}
1133
1134void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001135 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 Calibration& out = mCalibration;
1137
1138 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001139 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001140 std::string sizeCalibrationString;
1141 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001145 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001147 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001149 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001151 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001152 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001153 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 }
1155 }
1156
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001157 float sizeScale;
1158
1159 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1160 out.sizeScale = sizeScale;
1161 }
1162 float sizeBias;
1163 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1164 out.sizeBias = sizeBias;
1165 }
1166 bool sizeIsSummed;
1167 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1168 out.sizeIsSummed = sizeIsSummed;
1169 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170
1171 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001172 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001173 std::string pressureCalibrationString;
1174 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001176 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001178 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001180 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 } else if (pressureCalibrationString != "default") {
1182 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001183 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 }
1185 }
1186
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001187 float pressureScale;
1188 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1189 out.pressureScale = pressureScale;
1190 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191
1192 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001193 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001194 std::string orientationCalibrationString;
1195 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 } else if (orientationCalibrationString != "default") {
1203 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001204 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 }
1206 }
1207
1208 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001210 std::string distanceCalibrationString;
1211 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001215 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 } else if (distanceCalibrationString != "default") {
1217 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001218 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 }
1220 }
1221
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001222 float distanceScale;
1223 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1224 out.distanceScale = distanceScale;
1225 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226
Michael Wright227c5542020-07-02 18:30:52 +01001227 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001228 std::string coverageCalibrationString;
1229 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001231 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001233 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 } else if (coverageCalibrationString != "default") {
1235 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001236 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238 }
1239}
1240
1241void TouchInputMapper::resolveCalibration() {
1242 // Size
1243 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001244 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1245 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001248 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250
1251 // Pressure
1252 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001253 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1254 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001257 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
1259
1260 // Orientation
1261 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001262 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1263 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001266 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 }
1268
1269 // Distance
1270 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001271 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1272 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 }
1274 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001275 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 }
1277
1278 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001279 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1280 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 }
1282}
1283
1284void TouchInputMapper::dumpCalibration(std::string& dump) {
1285 dump += INDENT3 "Calibration:\n";
1286
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001287 dump += INDENT4 "touch.size.calibration: ";
1288 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001290 if (mCalibration.sizeScale) {
1291 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 }
1293
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001294 if (mCalibration.sizeBias) {
1295 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 }
1297
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001298 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001300 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 }
1302
1303 // Pressure
1304 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001305 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 dump += INDENT4 "touch.pressure.calibration: none\n";
1307 break;
Michael Wright227c5542020-07-02 18:30:52 +01001308 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 dump += INDENT4 "touch.pressure.calibration: physical\n";
1310 break;
Michael Wright227c5542020-07-02 18:30:52 +01001311 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1313 break;
1314 default:
1315 ALOG_ASSERT(false);
1316 }
1317
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001318 if (mCalibration.pressureScale) {
1319 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 }
1321
1322 // Orientation
1323 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001324 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.orientation.calibration: none\n";
1326 break;
Michael Wright227c5542020-07-02 18:30:52 +01001327 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1329 break;
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.orientation.calibration: vector\n";
1332 break;
1333 default:
1334 ALOG_ASSERT(false);
1335 }
1336
1337 // Distance
1338 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001339 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340 dump += INDENT4 "touch.distance.calibration: none\n";
1341 break;
Michael Wright227c5542020-07-02 18:30:52 +01001342 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 dump += INDENT4 "touch.distance.calibration: scaled\n";
1344 break;
1345 default:
1346 ALOG_ASSERT(false);
1347 }
1348
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001349 if (mCalibration.distanceScale) {
1350 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001351 }
1352
1353 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001354 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001355 dump += INDENT4 "touch.coverage.calibration: none\n";
1356 break;
Michael Wright227c5542020-07-02 18:30:52 +01001357 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001358 dump += INDENT4 "touch.coverage.calibration: box\n";
1359 break;
1360 default:
1361 ALOG_ASSERT(false);
1362 }
1363}
1364
1365void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1366 dump += INDENT3 "Affine Transformation:\n";
1367
1368 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1369 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1370 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1371 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1372 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1373 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1374}
1375
1376void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001377 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001378 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379}
1380
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001381std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001382 std::list<NotifyArgs> out = cancelTouch(when, when);
1383 updateTouchSpots();
1384
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001385 mCursorButtonAccumulator.reset(getDeviceContext());
1386 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001387 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001388
1389 mPointerVelocityControl.reset();
1390 mWheelXVelocityControl.reset();
1391 mWheelYVelocityControl.reset();
1392
1393 mRawStatesPending.clear();
1394 mCurrentRawState.clear();
1395 mCurrentCookedState.clear();
1396 mLastRawState.clear();
1397 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001398 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001399 mSentHoverEnter = false;
1400 mHavePointerIds = false;
1401 mCurrentMotionAborted = false;
1402 mDownTime = 0;
1403
1404 mCurrentVirtualKey.down = false;
1405
1406 mPointerGesture.reset();
1407 mPointerSimple.reset();
1408 resetExternalStylus();
1409
1410 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001411 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001412 mPointerController->clearSpots();
1413 }
1414
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001415 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001416}
1417
1418void TouchInputMapper::resetExternalStylus() {
1419 mExternalStylusState.clear();
1420 mExternalStylusId = -1;
1421 mExternalStylusFusionTimeout = LLONG_MAX;
1422 mExternalStylusDataPending = false;
1423}
1424
1425void TouchInputMapper::clearStylusDataPendingFlags() {
1426 mExternalStylusDataPending = false;
1427 mExternalStylusFusionTimeout = LLONG_MAX;
1428}
1429
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001430std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431 mCursorButtonAccumulator.process(rawEvent);
1432 mCursorScrollAccumulator.process(rawEvent);
1433 mTouchButtonAccumulator.process(rawEvent);
1434
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001435 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001437 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001439 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440}
1441
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001442std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1443 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001444 if (mDeviceMode == DeviceMode::DISABLED) {
1445 // Only save the last pending state when the device is disabled.
1446 mRawStatesPending.clear();
1447 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001448 // Push a new state.
1449 mRawStatesPending.emplace_back();
1450
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001451 RawState& next = mRawStatesPending.back();
1452 next.clear();
1453 next.when = when;
1454 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455
1456 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001457 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001458 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1459
1460 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001461 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1462 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001463 mCursorScrollAccumulator.finishSync();
1464
1465 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001466 syncTouch(when, &next);
1467
1468 // The last RawState is the actually second to last, since we just added a new state
1469 const RawState& last =
1470 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001471
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001472 next.when = applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1473 last.when);
1474
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001475 // Assign pointer ids.
1476 if (!mHavePointerIds) {
1477 assignPointerIds(last, next);
1478 }
1479
Harry Cutts45483602022-08-24 14:36:48 +00001480 ALOGD_IF(DEBUG_RAW_EVENTS,
1481 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1482 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1483 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1484 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1485 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1486 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001487
Arthur Hung9ad18942021-06-19 02:04:46 +00001488 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1489 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1490 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1491 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1492 next.rawPointerData.hoveringIdBits.value);
1493 }
1494
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001495 out += processRawTouches(false /*timeout*/);
1496 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001497}
1498
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001499std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1500 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001501 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001502 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001503 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001504 }
1505
1506 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1507 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1508 // touching the current state will only observe the events that have been dispatched to the
1509 // rest of the pipeline.
1510 const size_t N = mRawStatesPending.size();
1511 size_t count;
1512 for (count = 0; count < N; count++) {
1513 const RawState& next = mRawStatesPending[count];
1514
1515 // A failure to assign the stylus id means that we're waiting on stylus data
1516 // and so should defer the rest of the pipeline.
1517 if (assignExternalStylusId(next, timeout)) {
1518 break;
1519 }
1520
1521 // All ready to go.
1522 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001523 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 if (mCurrentRawState.when < mLastRawState.when) {
1525 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001526 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001527 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001528 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001529 }
1530 if (count != 0) {
1531 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1532 }
1533
1534 if (mExternalStylusDataPending) {
1535 if (timeout) {
1536 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1537 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001538 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001539 ALOGD_IF(DEBUG_STYLUS_FUSION,
1540 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001541 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001542 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001543 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1544 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1545 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1546 }
1547 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001548 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001549}
1550
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001551std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1552 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001553 // Always start with a clean state.
1554 mCurrentCookedState.clear();
1555
1556 // Apply stylus buttons to current raw state.
1557 applyExternalStylusButtonState(when);
1558
1559 // Handle policy on initial down or hover events.
1560 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1561 mCurrentRawState.rawPointerData.pointerCount != 0;
1562
1563 uint32_t policyFlags = 0;
1564 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1565 if (initialDown || buttonsPressed) {
1566 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001567 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001568 getContext()->fadePointer();
1569 }
1570
1571 if (mParameters.wake) {
1572 policyFlags |= POLICY_FLAG_WAKE;
1573 }
1574 }
1575
1576 // Consume raw off-screen touches before cooking pointer data.
1577 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001578 bool consumed;
1579 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1580 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001581 mCurrentRawState.rawPointerData.clear();
1582 }
1583
1584 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1585 // with cooked pointer data that has the same ids and indices as the raw data.
1586 // The following code can use either the raw or cooked data, as needed.
1587 cookPointerData();
1588
1589 // Apply stylus pressure to current cooked state.
1590 applyExternalStylusTouchState(when);
1591
1592 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001593 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1594 mSource, mViewport.displayId, policyFlags,
1595 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596
1597 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001598 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001599 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1600 uint32_t id = idBits.clearFirstMarkedBit();
1601 const RawPointerData::Pointer& pointer =
1602 mCurrentRawState.rawPointerData.pointerForId(id);
1603 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1604 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1605 mCurrentCookedState.stylusIdBits.markBit(id);
1606 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1607 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1608 mCurrentCookedState.fingerIdBits.markBit(id);
1609 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1610 mCurrentCookedState.mouseIdBits.markBit(id);
1611 }
1612 }
1613 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1614 uint32_t id = idBits.clearFirstMarkedBit();
1615 const RawPointerData::Pointer& pointer =
1616 mCurrentRawState.rawPointerData.pointerForId(id);
1617 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1618 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1619 mCurrentCookedState.stylusIdBits.markBit(id);
1620 }
1621 }
1622
1623 // Stylus takes precedence over all tools, then mouse, then finger.
1624 PointerUsage pointerUsage = mPointerUsage;
1625 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1626 mCurrentCookedState.mouseIdBits.clear();
1627 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001628 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1630 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001631 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1633 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001634 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001635 }
1636
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001637 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001638 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001639 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001640 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001641 out += dispatchButtonRelease(when, readTime, policyFlags);
1642 out += dispatchHoverExit(when, readTime, policyFlags);
1643 out += dispatchTouches(when, readTime, policyFlags);
1644 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1645 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001646 }
1647
1648 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1649 mCurrentMotionAborted = false;
1650 }
1651 }
1652
1653 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001654 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1655 mSource, mViewport.displayId, policyFlags,
1656 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001657
1658 // Clear some transient state.
1659 mCurrentRawState.rawVScroll = 0;
1660 mCurrentRawState.rawHScroll = 0;
1661
1662 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001663 mLastRawState = mCurrentRawState;
1664 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001665 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001666}
1667
Garfield Tanc734e4f2021-01-15 20:01:39 -08001668void TouchInputMapper::updateTouchSpots() {
1669 if (!mConfig.showTouches || mPointerController == nullptr) {
1670 return;
1671 }
1672
1673 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1674 // clear touch spots.
1675 if (mDeviceMode != DeviceMode::DIRECT &&
1676 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1677 return;
1678 }
1679
1680 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1681 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1682
1683 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001684 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1685 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001686 mCurrentCookedState.cookedPointerData.touchingIdBits,
1687 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001688}
1689
1690bool TouchInputMapper::isTouchScreen() {
1691 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1692 mParameters.hasAssociatedDisplay;
1693}
1694
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001695void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001696 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001697 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1698 }
1699}
1700
1701void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1702 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1703 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1704
1705 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1706 float pressure = mExternalStylusState.pressure;
1707 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1708 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1709 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1710 }
1711 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1712 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1713
1714 PointerProperties& properties =
1715 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1716 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1717 properties.toolType = mExternalStylusState.toolType;
1718 }
1719 }
1720}
1721
1722bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001723 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001724 return false;
1725 }
1726
1727 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1728 state.rawPointerData.pointerCount != 0;
1729 if (initialDown) {
1730 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001731 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001732 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1733 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001734 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001735 resetExternalStylus();
1736 } else {
1737 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1738 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1739 }
Harry Cutts45483602022-08-24 14:36:48 +00001740 ALOGD_IF(DEBUG_STYLUS_FUSION,
1741 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1742 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001743 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1744 return true;
1745 }
1746 }
1747
1748 // Check if the stylus pointer has gone up.
1749 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001750 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001751 mExternalStylusId = -1;
1752 }
1753
1754 return false;
1755}
1756
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001757std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1758 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001759 if (mDeviceMode == DeviceMode::POINTER) {
1760 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001761 // Since this is a synthetic event, we can consider its latency to be zero
1762 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001763 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001764 }
Michael Wright227c5542020-07-02 18:30:52 +01001765 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001766 if (mExternalStylusFusionTimeout < when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001767 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001768 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1769 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1770 }
1771 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001772 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001773}
1774
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001775std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1776 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001777 mExternalStylusState.copyFrom(state);
1778 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1779 // We're either in the middle of a fused stream of data or we're waiting on data before
1780 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1781 // data.
1782 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001783 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001784 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001785 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001786}
1787
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001788std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1789 uint32_t policyFlags, bool& outConsumed) {
1790 outConsumed = false;
1791 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792 // Check for release of a virtual key.
1793 if (mCurrentVirtualKey.down) {
1794 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1795 // Pointer went up while virtual key was down.
1796 mCurrentVirtualKey.down = false;
1797 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001798 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1799 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1800 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001801 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1802 AKEY_EVENT_FLAG_FROM_SYSTEM |
1803 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001804 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001805 outConsumed = true;
1806 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001807 }
1808
1809 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1810 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1811 const RawPointerData::Pointer& pointer =
1812 mCurrentRawState.rawPointerData.pointerForId(id);
1813 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1814 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1815 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001816 outConsumed = true;
1817 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001818 }
1819 }
1820
1821 // Pointer left virtual key area or another pointer also went down.
1822 // Send key cancellation but do not consume the touch yet.
1823 // This is useful when the user swipes through from the virtual key area
1824 // into the main display surface.
1825 mCurrentVirtualKey.down = false;
1826 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001827 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1828 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001829 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1830 AKEY_EVENT_FLAG_FROM_SYSTEM |
1831 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1832 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001833 }
1834 }
1835
1836 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1837 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1838 // Pointer just went down. Check for virtual key press or off-screen touches.
1839 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1840 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001841 // Skip checking whether the pointer is inside the physical frame if the device is in
1842 // unscaled mode.
1843 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1844 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001845 // If exactly one pointer went down, check for virtual key hit.
1846 // Otherwise we will drop the entire stroke.
1847 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1848 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1849 if (virtualKey) {
1850 mCurrentVirtualKey.down = true;
1851 mCurrentVirtualKey.downTime = when;
1852 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1853 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1854 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001855 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1856 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001857
1858 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001859 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1860 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1861 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001862 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1863 AKEY_EVENT_ACTION_DOWN,
1864 AKEY_EVENT_FLAG_FROM_SYSTEM |
1865 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001866 }
1867 }
1868 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001869 outConsumed = true;
1870 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001871 }
1872 }
1873
1874 // Disable all virtual key touches that happen within a short time interval of the
1875 // most recent touch within the screen area. The idea is to filter out stray
1876 // virtual key presses when interacting with the touch screen.
1877 //
1878 // Problems we're trying to solve:
1879 //
1880 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1881 // virtual key area that is implemented by a separate touch panel and accidentally
1882 // triggers a virtual key.
1883 //
1884 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1885 // area and accidentally triggers a virtual key. This often happens when virtual keys
1886 // are layed out below the screen near to where the on screen keyboard's space bar
1887 // is displayed.
1888 if (mConfig.virtualKeyQuietTime > 0 &&
1889 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001890 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001891 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001892 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001893}
1894
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001895NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1896 uint32_t policyFlags, int32_t keyEventAction,
1897 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001898 int32_t keyCode = mCurrentVirtualKey.keyCode;
1899 int32_t scanCode = mCurrentVirtualKey.scanCode;
1900 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001901 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001902 policyFlags |= POLICY_FLAG_VIRTUAL;
1903
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001904 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1905 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1906 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907}
1908
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001909std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1910 uint32_t policyFlags) {
1911 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001912 if (mCurrentMotionAborted) {
1913 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001914 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001915 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001916 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1917 if (!currentIdBits.isEmpty()) {
1918 int32_t metaState = getContext()->getGlobalMetaState();
1919 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001921 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1922 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001923 mCurrentCookedState.cookedPointerData.pointerProperties,
1924 mCurrentCookedState.cookedPointerData.pointerCoords,
1925 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1926 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1927 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001928 mCurrentMotionAborted = true;
1929 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001930 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001931}
1932
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001933// Updates pointer coords and properties for pointers with specified ids that have moved.
1934// Returns true if any of them changed.
1935static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1936 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1937 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1938 BitSet32 idBits) {
1939 bool changed = false;
1940 while (!idBits.isEmpty()) {
1941 uint32_t id = idBits.clearFirstMarkedBit();
1942 uint32_t inIndex = inIdToIndex[id];
1943 uint32_t outIndex = outIdToIndex[id];
1944
1945 const PointerProperties& curInProperties = inProperties[inIndex];
1946 const PointerCoords& curInCoords = inCoords[inIndex];
1947 PointerProperties& curOutProperties = outProperties[outIndex];
1948 PointerCoords& curOutCoords = outCoords[outIndex];
1949
1950 if (curInProperties != curOutProperties) {
1951 curOutProperties.copyFrom(curInProperties);
1952 changed = true;
1953 }
1954
1955 if (curInCoords != curOutCoords) {
1956 curOutCoords.copyFrom(curInCoords);
1957 changed = true;
1958 }
1959 }
1960 return changed;
1961}
1962
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001963std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1964 uint32_t policyFlags) {
1965 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001966 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1967 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1968 int32_t metaState = getContext()->getGlobalMetaState();
1969 int32_t buttonState = mCurrentCookedState.buttonState;
1970
1971 if (currentIdBits == lastIdBits) {
1972 if (!currentIdBits.isEmpty()) {
1973 // No pointer id changes so this is a move event.
1974 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001975 out.push_back(
1976 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1977 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1978 mCurrentCookedState.cookedPointerData.pointerProperties,
1979 mCurrentCookedState.cookedPointerData.pointerCoords,
1980 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1981 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1982 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001983 }
1984 } else {
1985 // There may be pointers going up and pointers going down and pointers moving
1986 // all at the same time.
1987 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1988 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1989 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1990 BitSet32 dispatchedIdBits(lastIdBits.value);
1991
1992 // Update last coordinates of pointers that have moved so that we observe the new
1993 // pointer positions at the same time as other pointers that have just gone up.
1994 bool moveNeeded =
1995 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1996 mCurrentCookedState.cookedPointerData.pointerCoords,
1997 mCurrentCookedState.cookedPointerData.idToIndex,
1998 mLastCookedState.cookedPointerData.pointerProperties,
1999 mLastCookedState.cookedPointerData.pointerCoords,
2000 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2001 if (buttonState != mLastCookedState.buttonState) {
2002 moveNeeded = true;
2003 }
2004
2005 // Dispatch pointer up events.
2006 while (!upIdBits.isEmpty()) {
2007 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002008 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002009 if (isCanceled) {
2010 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2011 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002012 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2013 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2014 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2015 buttonState, 0,
2016 mLastCookedState.cookedPointerData.pointerProperties,
2017 mLastCookedState.cookedPointerData.pointerCoords,
2018 mLastCookedState.cookedPointerData.idToIndex,
2019 dispatchedIdBits, upId, mOrientedXPrecision,
2020 mOrientedYPrecision, mDownTime,
2021 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002022 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002023 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002024 }
2025
2026 // Dispatch move events if any of the remaining pointers moved from their old locations.
2027 // Although applications receive new locations as part of individual pointer up
2028 // events, they do not generally handle them except when presented in a move event.
2029 if (moveNeeded && !moveIdBits.isEmpty()) {
2030 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002031 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2032 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2033 mCurrentCookedState.cookedPointerData.pointerProperties,
2034 mCurrentCookedState.cookedPointerData.pointerCoords,
2035 mCurrentCookedState.cookedPointerData.idToIndex,
2036 dispatchedIdBits, -1, mOrientedXPrecision,
2037 mOrientedYPrecision, mDownTime,
2038 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002039 }
2040
2041 // Dispatch pointer down events using the new pointer locations.
2042 while (!downIdBits.isEmpty()) {
2043 uint32_t downId = downIdBits.clearFirstMarkedBit();
2044 dispatchedIdBits.markBit(downId);
2045
2046 if (dispatchedIdBits.count() == 1) {
2047 // First pointer is going down. Set down time.
2048 mDownTime = when;
2049 }
2050
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002051 out.push_back(
2052 dispatchMotion(when, readTime, policyFlags, mSource,
2053 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2054 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2055 mCurrentCookedState.cookedPointerData.pointerCoords,
2056 mCurrentCookedState.cookedPointerData.idToIndex,
2057 dispatchedIdBits, downId, mOrientedXPrecision,
2058 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002059 }
2060 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002061 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002062}
2063
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002064std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2065 uint32_t policyFlags) {
2066 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002067 if (mSentHoverEnter &&
2068 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2069 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2070 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002071 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2072 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2073 mLastCookedState.buttonState, 0,
2074 mLastCookedState.cookedPointerData.pointerProperties,
2075 mLastCookedState.cookedPointerData.pointerCoords,
2076 mLastCookedState.cookedPointerData.idToIndex,
2077 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2078 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2079 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002080 mSentHoverEnter = false;
2081 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002082 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002083}
2084
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002085std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2086 uint32_t policyFlags) {
2087 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002088 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2089 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2090 int32_t metaState = getContext()->getGlobalMetaState();
2091 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002092 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2093 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2094 mCurrentRawState.buttonState, 0,
2095 mCurrentCookedState.cookedPointerData.pointerProperties,
2096 mCurrentCookedState.cookedPointerData.pointerCoords,
2097 mCurrentCookedState.cookedPointerData.idToIndex,
2098 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2099 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2100 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002101 mSentHoverEnter = true;
2102 }
2103
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002104 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2105 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2106 mCurrentRawState.buttonState, 0,
2107 mCurrentCookedState.cookedPointerData.pointerProperties,
2108 mCurrentCookedState.cookedPointerData.pointerCoords,
2109 mCurrentCookedState.cookedPointerData.idToIndex,
2110 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2111 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2112 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002114 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002115}
2116
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002117std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2118 uint32_t policyFlags) {
2119 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002120 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2121 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2122 const int32_t metaState = getContext()->getGlobalMetaState();
2123 int32_t buttonState = mLastCookedState.buttonState;
2124 while (!releasedButtons.isEmpty()) {
2125 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2126 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002127 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2128 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2129 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002130 mLastCookedState.cookedPointerData.pointerProperties,
2131 mLastCookedState.cookedPointerData.pointerCoords,
2132 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002133 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2134 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002135 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002136 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002137}
2138
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002139std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2140 uint32_t policyFlags) {
2141 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002142 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2143 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2144 const int32_t metaState = getContext()->getGlobalMetaState();
2145 int32_t buttonState = mLastCookedState.buttonState;
2146 while (!pressedButtons.isEmpty()) {
2147 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2148 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002149 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2150 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2151 buttonState, 0,
2152 mCurrentCookedState.cookedPointerData.pointerProperties,
2153 mCurrentCookedState.cookedPointerData.pointerCoords,
2154 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2155 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2156 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002158 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002159}
2160
2161const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2162 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2163 return cookedPointerData.touchingIdBits;
2164 }
2165 return cookedPointerData.hoveringIdBits;
2166}
2167
2168void TouchInputMapper::cookPointerData() {
2169 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2170
2171 mCurrentCookedState.cookedPointerData.clear();
2172 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2173 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2174 mCurrentRawState.rawPointerData.hoveringIdBits;
2175 mCurrentCookedState.cookedPointerData.touchingIdBits =
2176 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002177 mCurrentCookedState.cookedPointerData.canceledIdBits =
2178 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002179
2180 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2181 mCurrentCookedState.buttonState = 0;
2182 } else {
2183 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2184 }
2185
2186 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002187 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002188 for (uint32_t i = 0; i < currentPointerCount; i++) {
2189 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2190
2191 // Size
2192 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2193 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002194 case Calibration::SizeCalibration::GEOMETRIC:
2195 case Calibration::SizeCalibration::DIAMETER:
2196 case Calibration::SizeCalibration::BOX:
2197 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002198 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2199 touchMajor = in.touchMajor;
2200 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2201 toolMajor = in.toolMajor;
2202 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2203 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2204 : in.touchMajor;
2205 } else if (mRawPointerAxes.touchMajor.valid) {
2206 toolMajor = touchMajor = in.touchMajor;
2207 toolMinor = touchMinor =
2208 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2209 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2210 : in.touchMajor;
2211 } else if (mRawPointerAxes.toolMajor.valid) {
2212 touchMajor = toolMajor = in.toolMajor;
2213 touchMinor = toolMinor =
2214 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2215 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2216 : in.toolMajor;
2217 } else {
2218 ALOG_ASSERT(false,
2219 "No touch or tool axes. "
2220 "Size calibration should have been resolved to NONE.");
2221 touchMajor = 0;
2222 touchMinor = 0;
2223 toolMajor = 0;
2224 toolMinor = 0;
2225 size = 0;
2226 }
2227
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002228 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002229 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2230 if (touchingCount > 1) {
2231 touchMajor /= touchingCount;
2232 touchMinor /= touchingCount;
2233 toolMajor /= touchingCount;
2234 toolMinor /= touchingCount;
2235 size /= touchingCount;
2236 }
2237 }
2238
Michael Wright227c5542020-07-02 18:30:52 +01002239 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002240 touchMajor *= mGeometricScale;
2241 touchMinor *= mGeometricScale;
2242 toolMajor *= mGeometricScale;
2243 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002244 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002245 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2246 touchMinor = touchMajor;
2247 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2248 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002249 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002250 touchMinor = touchMajor;
2251 toolMinor = toolMajor;
2252 }
2253
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002254 mCalibration.applySizeScaleAndBias(touchMajor);
2255 mCalibration.applySizeScaleAndBias(touchMinor);
2256 mCalibration.applySizeScaleAndBias(toolMajor);
2257 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002258 size *= mSizeScale;
2259 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002260 case Calibration::SizeCalibration::DEFAULT:
2261 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2262 break;
2263 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002264 touchMajor = 0;
2265 touchMinor = 0;
2266 toolMajor = 0;
2267 toolMinor = 0;
2268 size = 0;
2269 break;
2270 }
2271
2272 // Pressure
2273 float pressure;
2274 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002275 case Calibration::PressureCalibration::PHYSICAL:
2276 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002277 pressure = in.pressure * mPressureScale;
2278 break;
2279 default:
2280 pressure = in.isHovering ? 0 : 1;
2281 break;
2282 }
2283
2284 // Tilt and Orientation
2285 float tilt;
2286 float orientation;
2287 if (mHaveTilt) {
2288 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2289 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2290 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2291 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2292 } else {
2293 tilt = 0;
2294
2295 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002296 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 orientation = in.orientation * mOrientationScale;
2298 break;
Michael Wright227c5542020-07-02 18:30:52 +01002299 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002300 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2301 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2302 if (c1 != 0 || c2 != 0) {
2303 orientation = atan2f(c1, c2) * 0.5f;
2304 float confidence = hypotf(c1, c2);
2305 float scale = 1.0f + confidence / 16.0f;
2306 touchMajor *= scale;
2307 touchMinor /= scale;
2308 toolMajor *= scale;
2309 toolMinor /= scale;
2310 } else {
2311 orientation = 0;
2312 }
2313 break;
2314 }
2315 default:
2316 orientation = 0;
2317 }
2318 }
2319
2320 // Distance
2321 float distance;
2322 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002323 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002324 distance = in.distance * mDistanceScale;
2325 break;
2326 default:
2327 distance = 0;
2328 }
2329
2330 // Coverage
2331 int32_t rawLeft, rawTop, rawRight, rawBottom;
2332 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002333 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002334 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2335 rawRight = in.toolMinor & 0x0000ffff;
2336 rawBottom = in.toolMajor & 0x0000ffff;
2337 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2338 break;
2339 default:
2340 rawLeft = rawTop = rawRight = rawBottom = 0;
2341 break;
2342 }
2343
2344 // Adjust X,Y coords for device calibration
2345 // TODO: Adjust coverage coords?
2346 float xTransformed = in.x, yTransformed = in.y;
2347 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002348 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349
Prabir Pradhan1728b212021-10-19 16:00:03 -07002350 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 float left, top, right, bottom;
2352
Prabir Pradhan1728b212021-10-19 16:00:03 -07002353 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002355 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2356 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2357 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2358 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002360 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002362 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002363 }
2364 break;
2365 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2367 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002368 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2369 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002371 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002373 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 }
2375 break;
2376 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2378 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002379 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2380 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002382 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002384 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 }
2386 break;
2387 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002388 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2389 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2390 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2391 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 break;
2393 }
2394
2395 // Write output coords.
2396 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2397 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002398 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2402 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2403 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2404 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2405 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2406 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002407 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002408 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2409 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2410 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2411 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2412 } else {
2413 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2414 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2415 }
2416
Chris Ye364fdb52020-08-05 15:07:56 -07002417 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002418 uint32_t id = in.id;
2419 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2420 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2421 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2422 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2423 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2424 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2425 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2426 }
2427
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002428 // Write output properties.
2429 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002430 properties.clear();
2431 properties.id = id;
2432 properties.toolType = in.toolType;
2433
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002434 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002435 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002436 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002437 }
2438}
2439
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002440std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2441 uint32_t policyFlags,
2442 PointerUsage pointerUsage) {
2443 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002444 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002445 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002446 mPointerUsage = pointerUsage;
2447 }
2448
2449 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002450 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002451 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452 break;
Michael Wright227c5542020-07-02 18:30:52 +01002453 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002454 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002455 break;
Michael Wright227c5542020-07-02 18:30:52 +01002456 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002457 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 break;
Michael Wright227c5542020-07-02 18:30:52 +01002459 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 break;
2461 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002462 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463}
2464
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002465std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2466 uint32_t policyFlags) {
2467 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002469 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002470 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002471 break;
Michael Wright227c5542020-07-02 18:30:52 +01002472 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 break;
Michael Wright227c5542020-07-02 18:30:52 +01002475 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002476 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002477 break;
Michael Wright227c5542020-07-02 18:30:52 +01002478 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 break;
2480 }
2481
Michael Wright227c5542020-07-02 18:30:52 +01002482 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002483 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002484}
2485
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002486std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2487 uint32_t policyFlags,
2488 bool isTimeout) {
2489 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 // Update current gesture coordinates.
2491 bool cancelPreviousGesture, finishPreviousGesture;
2492 bool sendEvents =
2493 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2494 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002495 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496 }
2497 if (finishPreviousGesture) {
2498 cancelPreviousGesture = false;
2499 }
2500
2501 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002502 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002503 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 if (finishPreviousGesture || cancelPreviousGesture) {
2505 mPointerController->clearSpots();
2506 }
2507
Michael Wright227c5542020-07-02 18:30:52 +01002508 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002509 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2510 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002511 mPointerGesture.currentGestureIdBits,
2512 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002513 }
2514 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002515 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516 }
2517
2518 // Show or hide the pointer if needed.
2519 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002520 case PointerGesture::Mode::NEUTRAL:
2521 case PointerGesture::Mode::QUIET:
2522 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2523 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002525 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002526 }
2527 break;
Michael Wright227c5542020-07-02 18:30:52 +01002528 case PointerGesture::Mode::TAP:
2529 case PointerGesture::Mode::TAP_DRAG:
2530 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2531 case PointerGesture::Mode::HOVER:
2532 case PointerGesture::Mode::PRESS:
2533 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 // Unfade the pointer when the current gesture manipulates the
2535 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002536 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002537 break;
Michael Wright227c5542020-07-02 18:30:52 +01002538 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002539 // Fade the pointer when the current gesture manipulates a different
2540 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002541 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002542 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002543 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002544 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002545 }
2546 break;
2547 }
2548
2549 // Send events!
2550 int32_t metaState = getContext()->getGlobalMetaState();
2551 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002552 const MotionClassification classification =
2553 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2554 ? MotionClassification::TWO_FINGER_SWIPE
2555 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002556
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002557 uint32_t flags = 0;
2558
2559 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2560 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2561 }
2562
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002563 // Update last coordinates of pointers that have moved so that we observe the new
2564 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002565 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2566 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2567 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2568 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2569 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2570 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002571 bool moveNeeded = false;
2572 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2573 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2574 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2575 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2576 mPointerGesture.lastGestureIdBits.value);
2577 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2578 mPointerGesture.currentGestureCoords,
2579 mPointerGesture.currentGestureIdToIndex,
2580 mPointerGesture.lastGestureProperties,
2581 mPointerGesture.lastGestureCoords,
2582 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2583 if (buttonState != mLastCookedState.buttonState) {
2584 moveNeeded = true;
2585 }
2586 }
2587
2588 // Send motion events for all pointers that went up or were canceled.
2589 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2590 if (!dispatchedGestureIdBits.isEmpty()) {
2591 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002592 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002593 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002594 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002595 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2596 mPointerGesture.lastGestureProperties,
2597 mPointerGesture.lastGestureCoords,
2598 mPointerGesture.lastGestureIdToIndex,
2599 dispatchedGestureIdBits, -1, 0, 0,
2600 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002601
2602 dispatchedGestureIdBits.clear();
2603 } else {
2604 BitSet32 upGestureIdBits;
2605 if (finishPreviousGesture) {
2606 upGestureIdBits = dispatchedGestureIdBits;
2607 } else {
2608 upGestureIdBits.value =
2609 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2610 }
2611 while (!upGestureIdBits.isEmpty()) {
2612 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2613
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002614 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2615 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2616 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2617 mPointerGesture.lastGestureProperties,
2618 mPointerGesture.lastGestureCoords,
2619 mPointerGesture.lastGestureIdToIndex,
2620 dispatchedGestureIdBits, id, 0, 0,
2621 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002622
2623 dispatchedGestureIdBits.clearBit(id);
2624 }
2625 }
2626 }
2627
2628 // Send motion events for all pointers that moved.
2629 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002630 out.push_back(
2631 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2632 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2633 mPointerGesture.currentGestureProperties,
2634 mPointerGesture.currentGestureCoords,
2635 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2636 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002637 }
2638
2639 // Send motion events for all pointers that went down.
2640 if (down) {
2641 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2642 ~dispatchedGestureIdBits.value);
2643 while (!downGestureIdBits.isEmpty()) {
2644 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2645 dispatchedGestureIdBits.markBit(id);
2646
2647 if (dispatchedGestureIdBits.count() == 1) {
2648 mPointerGesture.downTime = when;
2649 }
2650
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002651 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2652 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2653 buttonState, 0, mPointerGesture.currentGestureProperties,
2654 mPointerGesture.currentGestureCoords,
2655 mPointerGesture.currentGestureIdToIndex,
2656 dispatchedGestureIdBits, id, 0, 0,
2657 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002658 }
2659 }
2660
2661 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002662 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002663 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2664 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2665 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2666 mPointerGesture.currentGestureProperties,
2667 mPointerGesture.currentGestureCoords,
2668 mPointerGesture.currentGestureIdToIndex,
2669 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2670 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002671 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2672 // Synthesize a hover move event after all pointers go up to indicate that
2673 // the pointer is hovering again even if the user is not currently touching
2674 // the touch pad. This ensures that a view will receive a fresh hover enter
2675 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002676 float x, y;
2677 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002678
2679 PointerProperties pointerProperties;
2680 pointerProperties.clear();
2681 pointerProperties.id = 0;
2682 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2683
2684 PointerCoords pointerCoords;
2685 pointerCoords.clear();
2686 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2687 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2688
2689 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002690 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2691 mSource, displayId, policyFlags,
2692 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2693 buttonState, MotionClassification::NONE,
2694 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2695 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2696 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002697 }
2698
2699 // Update state.
2700 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2701 if (!down) {
2702 mPointerGesture.lastGestureIdBits.clear();
2703 } else {
2704 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2705 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2706 uint32_t id = idBits.clearFirstMarkedBit();
2707 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2708 mPointerGesture.lastGestureProperties[index].copyFrom(
2709 mPointerGesture.currentGestureProperties[index]);
2710 mPointerGesture.lastGestureCoords[index].copyFrom(
2711 mPointerGesture.currentGestureCoords[index]);
2712 mPointerGesture.lastGestureIdToIndex[id] = index;
2713 }
2714 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002715 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002716}
2717
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002718std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2719 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002720 const MotionClassification classification =
2721 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2722 ? MotionClassification::TWO_FINGER_SWIPE
2723 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002724 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002725 // Cancel previously dispatches pointers.
2726 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2727 int32_t metaState = getContext()->getGlobalMetaState();
2728 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002729 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002730 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2731 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002732 mPointerGesture.lastGestureProperties,
2733 mPointerGesture.lastGestureCoords,
2734 mPointerGesture.lastGestureIdToIndex,
2735 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2736 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002737 }
2738
2739 // Reset the current pointer gesture.
2740 mPointerGesture.reset();
2741 mPointerVelocityControl.reset();
2742
2743 // Remove any current spots.
2744 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002745 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002746 mPointerController->clearSpots();
2747 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002748 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002749}
2750
2751bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2752 bool* outFinishPreviousGesture, bool isTimeout) {
2753 *outCancelPreviousGesture = false;
2754 *outFinishPreviousGesture = false;
2755
2756 // Handle TAP timeout.
2757 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002758 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002759
Michael Wright227c5542020-07-02 18:30:52 +01002760 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002761 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2762 // The tap/drag timeout has not yet expired.
2763 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2764 mConfig.pointerGestureTapDragInterval);
2765 } else {
2766 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002767 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002768 *outFinishPreviousGesture = true;
2769
2770 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002771 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002772 mPointerGesture.currentGestureIdBits.clear();
2773
2774 mPointerVelocityControl.reset();
2775 return true;
2776 }
2777 }
2778
2779 // We did not handle this timeout.
2780 return false;
2781 }
2782
2783 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2784 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2785
2786 // Update the velocity tracker.
2787 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002788 std::vector<float> positionsX;
2789 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002790 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002791 uint32_t id = idBits.clearFirstMarkedBit();
2792 const RawPointerData::Pointer& pointer =
2793 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002794 positionsX.push_back(pointer.x * mPointerXMovementScale);
2795 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002796 }
2797 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002798 {{AMOTION_EVENT_AXIS_X, positionsX},
2799 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002800 }
2801
2802 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2803 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002804 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2805 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2806 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002807 mPointerGesture.resetTap();
2808 }
2809
2810 // Pick a new active touch id if needed.
2811 // Choose an arbitrary pointer that just went down, if there is one.
2812 // Otherwise choose an arbitrary remaining pointer.
2813 // This guarantees we always have an active touch id when there is at least one pointer.
2814 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002815 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002816 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002817 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002818 mPointerGesture.firstTouchTime = when;
2819 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002820 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2821 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2822 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2823 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002825 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826
2827 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002828 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002829 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002830 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2831 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2832 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002833 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002834 *outFinishPreviousGesture = true;
2835 }
2836
2837 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002838 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002839 mPointerGesture.currentGestureIdBits.clear();
2840
2841 mPointerVelocityControl.reset();
2842 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2843 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2844 // The pointer follows the active touch point.
2845 // Emit DOWN, MOVE, UP events at the pointer location.
2846 //
2847 // Only the active touch matters; other fingers are ignored. This policy helps
2848 // to handle the case where the user places a second finger on the touch pad
2849 // to apply the necessary force to depress an integrated button below the surface.
2850 // We don't want the second finger to be delivered to applications.
2851 //
2852 // For this to work well, we need to make sure to track the pointer that is really
2853 // active. If the user first puts one finger down to click then adds another
2854 // finger to drag then the active pointer should switch to the finger that is
2855 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002856 ALOGD_IF(DEBUG_GESTURES,
2857 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2858 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002860 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002861 *outFinishPreviousGesture = true;
2862 mPointerGesture.activeGestureId = 0;
2863 }
2864
2865 // Switch pointers if needed.
2866 // Find the fastest pointer and follow it.
2867 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002868 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002870 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002871 ALOGD_IF(DEBUG_GESTURES,
2872 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2873 "bestSpeed=%0.3f",
2874 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 }
2876 }
2877
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002879 // When using spots, the click will occur at the position of the anchor
2880 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002881 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002882 } else {
2883 mPointerVelocityControl.reset();
2884 }
2885
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002886 float x, y;
2887 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002888
Michael Wright227c5542020-07-02 18:30:52 +01002889 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002890 mPointerGesture.currentGestureIdBits.clear();
2891 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2892 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2893 mPointerGesture.currentGestureProperties[0].clear();
2894 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2895 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2896 mPointerGesture.currentGestureCoords[0].clear();
2897 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2898 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2899 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2900 } else if (currentFingerCount == 0) {
2901 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002902 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903 *outFinishPreviousGesture = true;
2904 }
2905
2906 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2907 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2908 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002909 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2910 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002911 lastFingerCount == 1) {
2912 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002913 float x, y;
2914 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002915 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2916 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002917 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002918
2919 mPointerGesture.tapUpTime = when;
2920 getContext()->requestTimeoutAtTime(when +
2921 mConfig.pointerGestureTapDragInterval);
2922
2923 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002924 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002925 mPointerGesture.currentGestureIdBits.clear();
2926 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2927 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2928 mPointerGesture.currentGestureProperties[0].clear();
2929 mPointerGesture.currentGestureProperties[0].id =
2930 mPointerGesture.activeGestureId;
2931 mPointerGesture.currentGestureProperties[0].toolType =
2932 AMOTION_EVENT_TOOL_TYPE_FINGER;
2933 mPointerGesture.currentGestureCoords[0].clear();
2934 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2935 mPointerGesture.tapX);
2936 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2937 mPointerGesture.tapY);
2938 mPointerGesture.currentGestureCoords[0]
2939 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2940
2941 tapped = true;
2942 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002943 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2944 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 }
2946 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002947 if (DEBUG_GESTURES) {
2948 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2949 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2950 (when - mPointerGesture.tapDownTime) * 0.000001f);
2951 } else {
2952 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2953 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002955 }
2956 }
2957
2958 mPointerVelocityControl.reset();
2959
2960 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002961 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002962 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002963 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002964 mPointerGesture.currentGestureIdBits.clear();
2965 }
2966 } else if (currentFingerCount == 1) {
2967 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2968 // The pointer follows the active touch point.
2969 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2970 // When in TAP_DRAG, emit MOVE events at the pointer location.
2971 ALOG_ASSERT(activeTouchId >= 0);
2972
Michael Wright227c5542020-07-02 18:30:52 +01002973 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2974 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002975 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002976 float x, y;
2977 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2979 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002980 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002982 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2983 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984 }
2985 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002986 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2987 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 }
Michael Wright227c5542020-07-02 18:30:52 +01002989 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2990 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 }
2992
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002993 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002994 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002995 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 } else {
2997 mPointerVelocityControl.reset();
2998 }
2999
3000 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003001 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003002 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 down = true;
3004 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003005 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003006 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003007 *outFinishPreviousGesture = true;
3008 }
3009 mPointerGesture.activeGestureId = 0;
3010 down = false;
3011 }
3012
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003013 float x, y;
3014 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003015
3016 mPointerGesture.currentGestureIdBits.clear();
3017 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3018 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3019 mPointerGesture.currentGestureProperties[0].clear();
3020 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3021 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3022 mPointerGesture.currentGestureCoords[0].clear();
3023 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3024 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3025 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3026 down ? 1.0f : 0.0f);
3027
3028 if (lastFingerCount == 0 && currentFingerCount != 0) {
3029 mPointerGesture.resetTap();
3030 mPointerGesture.tapDownTime = when;
3031 mPointerGesture.tapX = x;
3032 mPointerGesture.tapY = y;
3033 }
3034 } else {
3035 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003036 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003037 }
3038
3039 mPointerController->setButtonState(mCurrentRawState.buttonState);
3040
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003041 if (DEBUG_GESTURES) {
3042 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3043 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3044 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3045 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3046 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3047 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3048 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3049 uint32_t id = idBits.clearFirstMarkedBit();
3050 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3051 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3052 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3053 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3054 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3055 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3056 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3057 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3058 }
3059 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3060 uint32_t id = idBits.clearFirstMarkedBit();
3061 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3062 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3063 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3064 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3065 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3066 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3067 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3068 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3069 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003070 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003071 return true;
3072}
3073
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003074bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3075 if (mPointerGesture.activeTouchId < 0) {
3076 mPointerGesture.resetQuietTime();
3077 return false;
3078 }
3079
3080 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3081 return true;
3082 }
3083
3084 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3085 bool isQuietTime = false;
3086 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3087 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3088 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3089 currentFingerCount < 2) {
3090 // Enter quiet time when exiting swipe or freeform state.
3091 // This is to prevent accidentally entering the hover state and flinging the
3092 // pointer when finishing a swipe and there is still one pointer left onscreen.
3093 isQuietTime = true;
3094 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3095 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3096 // Enter quiet time when releasing the button and there are still two or more
3097 // fingers down. This may indicate that one finger was used to press the button
3098 // but it has not gone up yet.
3099 isQuietTime = true;
3100 }
3101 if (isQuietTime) {
3102 mPointerGesture.quietTime = when;
3103 }
3104 return isQuietTime;
3105}
3106
3107std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3108 int32_t bestId = -1;
3109 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3110 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3111 uint32_t id = idBits.clearFirstMarkedBit();
3112 std::optional<float> vx =
3113 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3114 std::optional<float> vy =
3115 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3116 if (vx && vy) {
3117 float speed = hypotf(*vx, *vy);
3118 if (speed > bestSpeed) {
3119 bestId = id;
3120 bestSpeed = speed;
3121 }
3122 }
3123 }
3124 return std::make_pair(bestId, bestSpeed);
3125}
3126
3127void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3128 bool* finishPreviousGesture) {
3129 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3130 // to move before deciding what to do.
3131 //
3132 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3133 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3134 // just a press or long-press at the pointer location.
3135 //
3136 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3137 // pointer location.
3138 //
3139 // When the two fingers move enough or when additional fingers are added, we make a decision to
3140 // transition into SWIPE or FREEFORM mode accordingly.
3141 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3142 ALOG_ASSERT(activeTouchId >= 0);
3143
3144 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3145 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3146 bool settled =
3147 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3148 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3149 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3150 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3151 *finishPreviousGesture = true;
3152 } else if (!settled && currentFingerCount > lastFingerCount) {
3153 // Additional pointers have gone down but not yet settled.
3154 // Reset the gesture.
3155 ALOGD_IF(DEBUG_GESTURES,
3156 "Gestures: Resetting gesture since additional pointers went down for "
3157 "MULTITOUCH, settle time remaining %0.3fms",
3158 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3159 when) * 0.000001f);
3160 *cancelPreviousGesture = true;
3161 } else {
3162 // Continue previous gesture.
3163 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3164 }
3165
3166 if (*finishPreviousGesture || *cancelPreviousGesture) {
3167 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3168 mPointerGesture.activeGestureId = 0;
3169 mPointerGesture.referenceIdBits.clear();
3170 mPointerVelocityControl.reset();
3171
3172 // Use the centroid and pointer location as the reference points for the gesture.
3173 ALOGD_IF(DEBUG_GESTURES,
3174 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3175 "%0.3fms",
3176 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3177 when) * 0.000001f);
3178 mCurrentRawState.rawPointerData
3179 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3180 &mPointerGesture.referenceTouchY);
3181 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3182 &mPointerGesture.referenceGestureY);
3183 }
3184
3185 // Clear the reference deltas for fingers not yet included in the reference calculation.
3186 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3187 ~mPointerGesture.referenceIdBits.value);
3188 !idBits.isEmpty();) {
3189 uint32_t id = idBits.clearFirstMarkedBit();
3190 mPointerGesture.referenceDeltas[id].dx = 0;
3191 mPointerGesture.referenceDeltas[id].dy = 0;
3192 }
3193 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3194
3195 // Add delta for all fingers and calculate a common movement delta.
3196 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3197 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3198 mCurrentCookedState.fingerIdBits.value);
3199 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3200 bool first = (idBits == commonIdBits);
3201 uint32_t id = idBits.clearFirstMarkedBit();
3202 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3203 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3204 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3205 delta.dx += cpd.x - lpd.x;
3206 delta.dy += cpd.y - lpd.y;
3207
3208 if (first) {
3209 commonDeltaRawX = delta.dx;
3210 commonDeltaRawY = delta.dy;
3211 } else {
3212 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3213 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3214 }
3215 }
3216
3217 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3218 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3219 float dist[MAX_POINTER_ID + 1];
3220 int32_t distOverThreshold = 0;
3221 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3222 uint32_t id = idBits.clearFirstMarkedBit();
3223 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3224 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3225 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3226 distOverThreshold += 1;
3227 }
3228 }
3229
3230 // Only transition when at least two pointers have moved further than
3231 // the minimum distance threshold.
3232 if (distOverThreshold >= 2) {
3233 if (currentFingerCount > 2) {
3234 // There are more than two pointers, switch to FREEFORM.
3235 ALOGD_IF(DEBUG_GESTURES,
3236 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3237 currentFingerCount);
3238 *cancelPreviousGesture = true;
3239 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3240 } else {
3241 // There are exactly two pointers.
3242 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3243 uint32_t id1 = idBits.clearFirstMarkedBit();
3244 uint32_t id2 = idBits.firstMarkedBit();
3245 const RawPointerData::Pointer& p1 =
3246 mCurrentRawState.rawPointerData.pointerForId(id1);
3247 const RawPointerData::Pointer& p2 =
3248 mCurrentRawState.rawPointerData.pointerForId(id2);
3249 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3250 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3251 // There are two pointers but they are too far apart for a SWIPE,
3252 // switch to FREEFORM.
3253 ALOGD_IF(DEBUG_GESTURES,
3254 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3255 mutualDistance, mPointerGestureMaxSwipeWidth);
3256 *cancelPreviousGesture = true;
3257 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3258 } else {
3259 // There are two pointers. Wait for both pointers to start moving
3260 // before deciding whether this is a SWIPE or FREEFORM gesture.
3261 float dist1 = dist[id1];
3262 float dist2 = dist[id2];
3263 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3264 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3265 // Calculate the dot product of the displacement vectors.
3266 // When the vectors are oriented in approximately the same direction,
3267 // the angle betweeen them is near zero and the cosine of the angle
3268 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3269 // mag(v2).
3270 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3271 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3272 float dx1 = delta1.dx * mPointerXZoomScale;
3273 float dy1 = delta1.dy * mPointerYZoomScale;
3274 float dx2 = delta2.dx * mPointerXZoomScale;
3275 float dy2 = delta2.dy * mPointerYZoomScale;
3276 float dot = dx1 * dx2 + dy1 * dy2;
3277 float cosine = dot / (dist1 * dist2); // denominator always > 0
3278 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3279 // Pointers are moving in the same direction. Switch to SWIPE.
3280 ALOGD_IF(DEBUG_GESTURES,
3281 "Gestures: PRESS transitioned to SWIPE, "
3282 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3283 "cosine %0.3f >= %0.3f",
3284 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3285 mConfig.pointerGestureMultitouchMinDistance, cosine,
3286 mConfig.pointerGestureSwipeTransitionAngleCosine);
3287 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3288 } else {
3289 // Pointers are moving in different directions. Switch to FREEFORM.
3290 ALOGD_IF(DEBUG_GESTURES,
3291 "Gestures: PRESS transitioned to FREEFORM, "
3292 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3293 "cosine %0.3f < %0.3f",
3294 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3295 mConfig.pointerGestureMultitouchMinDistance, cosine,
3296 mConfig.pointerGestureSwipeTransitionAngleCosine);
3297 *cancelPreviousGesture = true;
3298 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3299 }
3300 }
3301 }
3302 }
3303 }
3304 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3305 // Switch from SWIPE to FREEFORM if additional pointers go down.
3306 // Cancel previous gesture.
3307 if (currentFingerCount > 2) {
3308 ALOGD_IF(DEBUG_GESTURES,
3309 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3310 currentFingerCount);
3311 *cancelPreviousGesture = true;
3312 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3313 }
3314 }
3315
3316 // Move the reference points based on the overall group motion of the fingers
3317 // except in PRESS mode while waiting for a transition to occur.
3318 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3319 (commonDeltaRawX || commonDeltaRawY)) {
3320 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3321 uint32_t id = idBits.clearFirstMarkedBit();
3322 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3323 delta.dx = 0;
3324 delta.dy = 0;
3325 }
3326
3327 mPointerGesture.referenceTouchX += commonDeltaRawX;
3328 mPointerGesture.referenceTouchY += commonDeltaRawY;
3329
3330 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3331 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3332
3333 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3334 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3335
3336 mPointerGesture.referenceGestureX += commonDeltaX;
3337 mPointerGesture.referenceGestureY += commonDeltaY;
3338 }
3339
3340 // Report gestures.
3341 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3342 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3343 // PRESS or SWIPE mode.
3344 ALOGD_IF(DEBUG_GESTURES,
3345 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3346 "currentTouchPointerCount=%d",
3347 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3348 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3349
3350 mPointerGesture.currentGestureIdBits.clear();
3351 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3352 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3353 mPointerGesture.currentGestureProperties[0].clear();
3354 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3355 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3356 mPointerGesture.currentGestureCoords[0].clear();
3357 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3358 mPointerGesture.referenceGestureX);
3359 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3360 mPointerGesture.referenceGestureY);
3361 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3362 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3363 float xOffset = static_cast<float>(commonDeltaRawX) /
3364 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3365 float yOffset = static_cast<float>(commonDeltaRawY) /
3366 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3367 mPointerGesture.currentGestureCoords[0]
3368 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3369 mPointerGesture.currentGestureCoords[0]
3370 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3371 }
3372 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3373 // FREEFORM mode.
3374 ALOGD_IF(DEBUG_GESTURES,
3375 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3376 "currentTouchPointerCount=%d",
3377 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3378 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3379
3380 mPointerGesture.currentGestureIdBits.clear();
3381
3382 BitSet32 mappedTouchIdBits;
3383 BitSet32 usedGestureIdBits;
3384 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3385 // Initially, assign the active gesture id to the active touch point
3386 // if there is one. No other touch id bits are mapped yet.
3387 if (!*cancelPreviousGesture) {
3388 mappedTouchIdBits.markBit(activeTouchId);
3389 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3390 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3391 mPointerGesture.activeGestureId;
3392 } else {
3393 mPointerGesture.activeGestureId = -1;
3394 }
3395 } else {
3396 // Otherwise, assume we mapped all touches from the previous frame.
3397 // Reuse all mappings that are still applicable.
3398 mappedTouchIdBits.value =
3399 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3400 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3401
3402 // Check whether we need to choose a new active gesture id because the
3403 // current went went up.
3404 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3405 ~mCurrentCookedState.fingerIdBits.value);
3406 !upTouchIdBits.isEmpty();) {
3407 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3408 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3409 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3410 mPointerGesture.activeGestureId = -1;
3411 break;
3412 }
3413 }
3414 }
3415
3416 ALOGD_IF(DEBUG_GESTURES,
3417 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3418 "activeGestureId=%d",
3419 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3420
3421 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3422 for (uint32_t i = 0; i < currentFingerCount; i++) {
3423 uint32_t touchId = idBits.clearFirstMarkedBit();
3424 uint32_t gestureId;
3425 if (!mappedTouchIdBits.hasBit(touchId)) {
3426 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3427 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3428 ALOGD_IF(DEBUG_GESTURES,
3429 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3430 gestureId);
3431 } else {
3432 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3433 ALOGD_IF(DEBUG_GESTURES,
3434 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3435 touchId, gestureId);
3436 }
3437 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3438 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3439
3440 const RawPointerData::Pointer& pointer =
3441 mCurrentRawState.rawPointerData.pointerForId(touchId);
3442 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3443 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3444 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3445
3446 mPointerGesture.currentGestureProperties[i].clear();
3447 mPointerGesture.currentGestureProperties[i].id = gestureId;
3448 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3449 mPointerGesture.currentGestureCoords[i].clear();
3450 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3451 mPointerGesture.referenceGestureX +
3452 deltaX);
3453 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3454 mPointerGesture.referenceGestureY +
3455 deltaY);
3456 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3457 }
3458
3459 if (mPointerGesture.activeGestureId < 0) {
3460 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3461 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3462 mPointerGesture.activeGestureId);
3463 }
3464 }
3465}
3466
Harry Cutts714d1ad2022-08-24 16:36:43 +00003467void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3468 const RawPointerData::Pointer& currentPointer =
3469 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3470 const RawPointerData::Pointer& lastPointer =
3471 mLastRawState.rawPointerData.pointerForId(pointerId);
3472 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3473 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3474
3475 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3476 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3477
3478 mPointerController->move(deltaX, deltaY);
3479}
3480
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003481std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3482 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003483 mPointerSimple.currentCoords.clear();
3484 mPointerSimple.currentProperties.clear();
3485
3486 bool down, hovering;
3487 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3488 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3489 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003490 mPointerController
3491 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3492 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003493
3494 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3495 down = !hovering;
3496
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003497 float x, y;
3498 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003499 mPointerSimple.currentCoords.copyFrom(
3500 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3501 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3502 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3503 mPointerSimple.currentProperties.id = 0;
3504 mPointerSimple.currentProperties.toolType =
3505 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3506 } else {
3507 down = false;
3508 hovering = false;
3509 }
3510
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003511 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003512}
3513
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003514std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3515 uint32_t policyFlags) {
3516 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517}
3518
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003519std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3520 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003521 mPointerSimple.currentCoords.clear();
3522 mPointerSimple.currentProperties.clear();
3523
3524 bool down, hovering;
3525 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3526 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003528 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003529 } else {
3530 mPointerVelocityControl.reset();
3531 }
3532
3533 down = isPointerDown(mCurrentRawState.buttonState);
3534 hovering = !down;
3535
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003536 float x, y;
3537 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003538 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003539 mPointerSimple.currentCoords.copyFrom(
3540 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3541 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3542 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3543 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3544 hovering ? 0.0f : 1.0f);
3545 mPointerSimple.currentProperties.id = 0;
3546 mPointerSimple.currentProperties.toolType =
3547 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3548 } else {
3549 mPointerVelocityControl.reset();
3550
3551 down = false;
3552 hovering = false;
3553 }
3554
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003555 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003556}
3557
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003558std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3559 uint32_t policyFlags) {
3560 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003561
3562 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003563
3564 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003565}
3566
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003567std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3568 uint32_t policyFlags, bool down,
3569 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003570 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3571 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003572 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003574
3575 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003576 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003577 mPointerController->clearSpots();
3578 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003579 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003580 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003581 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003582 }
Garfield Tan9514d782020-11-10 16:37:23 -08003583 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003584
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003585 float xCursorPosition, yCursorPosition;
3586 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003587
3588 if (mPointerSimple.down && !down) {
3589 mPointerSimple.down = false;
3590
3591 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003592 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3593 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3594 0, metaState, mLastRawState.buttonState,
3595 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3596 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3597 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3598 yCursorPosition, mPointerSimple.downTime,
3599 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003600 }
3601
3602 if (mPointerSimple.hovering && !hovering) {
3603 mPointerSimple.hovering = false;
3604
3605 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003606 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3607 mSource, displayId, policyFlags,
3608 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3609 mLastRawState.buttonState, MotionClassification::NONE,
3610 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3611 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3612 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3613 yCursorPosition, mPointerSimple.downTime,
3614 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003615 }
3616
3617 if (down) {
3618 if (!mPointerSimple.down) {
3619 mPointerSimple.down = true;
3620 mPointerSimple.downTime = when;
3621
3622 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003623 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3624 mSource, displayId, policyFlags,
3625 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3626 mCurrentRawState.buttonState, MotionClassification::NONE,
3627 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3628 &mPointerSimple.currentProperties,
3629 &mPointerSimple.currentCoords, mOrientedXPrecision,
3630 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3631 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003632 }
3633
3634 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003635 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3636 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3637 0, 0, metaState, mCurrentRawState.buttonState,
3638 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3639 &mPointerSimple.currentProperties,
3640 &mPointerSimple.currentCoords, mOrientedXPrecision,
3641 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3642 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003643 }
3644
3645 if (hovering) {
3646 if (!mPointerSimple.hovering) {
3647 mPointerSimple.hovering = true;
3648
3649 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003650 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3651 mSource, displayId, policyFlags,
3652 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3653 mCurrentRawState.buttonState, MotionClassification::NONE,
3654 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3655 &mPointerSimple.currentProperties,
3656 &mPointerSimple.currentCoords, mOrientedXPrecision,
3657 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3658 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003659 }
3660
3661 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003662 out.push_back(
3663 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3664 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3665 metaState, mCurrentRawState.buttonState,
3666 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3667 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3668 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3669 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003670 }
3671
3672 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3673 float vscroll = mCurrentRawState.rawVScroll;
3674 float hscroll = mCurrentRawState.rawHScroll;
3675 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3676 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3677
3678 // Send scroll.
3679 PointerCoords pointerCoords;
3680 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3681 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3682 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3683
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003684 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3685 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3686 0, 0, metaState, mCurrentRawState.buttonState,
3687 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3688 &mPointerSimple.currentProperties, &pointerCoords,
3689 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3690 yCursorPosition, mPointerSimple.downTime,
3691 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003692 }
3693
3694 // Save state.
3695 if (down || hovering) {
3696 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3697 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003698 mPointerSimple.displayId = displayId;
3699 mPointerSimple.source = mSource;
3700 mPointerSimple.lastCursorX = xCursorPosition;
3701 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003702 } else {
3703 mPointerSimple.reset();
3704 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003705 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003706}
3707
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003708std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3709 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003710 std::list<NotifyArgs> out;
3711 if (mPointerSimple.down || mPointerSimple.hovering) {
3712 int32_t metaState = getContext()->getGlobalMetaState();
3713 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3714 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3715 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3716 metaState, mLastRawState.buttonState,
3717 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3718 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3719 mOrientedXPrecision, mOrientedYPrecision,
3720 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3721 mPointerSimple.downTime,
3722 /* videoFrames */ {}));
3723 if (mPointerController != nullptr) {
3724 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3725 }
3726 }
3727 mPointerSimple.reset();
3728 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003729}
3730
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003731NotifyMotionArgs TouchInputMapper::dispatchMotion(
3732 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3733 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003734 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3735 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003736 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003737 PointerCoords pointerCoords[MAX_POINTERS];
3738 PointerProperties pointerProperties[MAX_POINTERS];
3739 uint32_t pointerCount = 0;
3740 while (!idBits.isEmpty()) {
3741 uint32_t id = idBits.clearFirstMarkedBit();
3742 uint32_t index = idToIndex[id];
3743 pointerProperties[pointerCount].copyFrom(properties[index]);
3744 pointerCoords[pointerCount].copyFrom(coords[index]);
3745
3746 if (changedId >= 0 && id == uint32_t(changedId)) {
3747 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3748 }
3749
3750 pointerCount += 1;
3751 }
3752
3753 ALOG_ASSERT(pointerCount != 0);
3754
3755 if (changedId >= 0 && pointerCount == 1) {
3756 // Replace initial down and final up action.
3757 // We can compare the action without masking off the changed pointer index
3758 // because we know the index is 0.
3759 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3760 action = AMOTION_EVENT_ACTION_DOWN;
3761 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003762 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3763 action = AMOTION_EVENT_ACTION_CANCEL;
3764 } else {
3765 action = AMOTION_EVENT_ACTION_UP;
3766 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003767 } else {
3768 // Can't happen.
3769 ALOG_ASSERT(false);
3770 }
3771 }
3772 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3773 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003774 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003775 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003776 }
3777 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3778 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003779 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003780 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003781 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003782 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3783 policyFlags, action, actionButton, flags, metaState, buttonState,
3784 classification, edgeFlags, pointerCount, pointerProperties,
3785 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3786 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003787}
3788
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003789std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3790 std::list<NotifyArgs> out;
3791 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3792 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3793 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003794}
3795
Prabir Pradhan1728b212021-10-19 16:00:03 -07003796// Transform input device coordinates to display panel coordinates.
3797void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003798 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3799 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3800
arthurhunga36b28e2020-12-29 20:28:15 +08003801 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3802 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3803
Prabir Pradhan1728b212021-10-19 16:00:03 -07003804 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003805 // 0 - no swap and reverse.
3806 // 90 - swap x/y and reverse y.
3807 // 180 - reverse x, y.
3808 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003809 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003810 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003811 x = xScaled;
3812 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003813 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003814 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003815 y = xScaledMax;
3816 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003817 break;
3818 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003819 x = xScaledMax;
3820 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003821 break;
3822 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003823 y = xScaled;
3824 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003825 break;
3826 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003827 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003828 }
3829}
3830
Prabir Pradhan1728b212021-10-19 16:00:03 -07003831bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003832 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3833 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3834
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003835 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003836 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003837 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003838 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003839}
3840
3841const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3842 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003843 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3844 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3845 "left=%d, top=%d, right=%d, bottom=%d",
3846 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3847 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003848
3849 if (virtualKey.isHit(x, y)) {
3850 return &virtualKey;
3851 }
3852 }
3853
3854 return nullptr;
3855}
3856
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003857void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3858 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3859 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003860
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003861 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003862
3863 if (currentPointerCount == 0) {
3864 // No pointers to assign.
3865 return;
3866 }
3867
3868 if (lastPointerCount == 0) {
3869 // All pointers are new.
3870 for (uint32_t i = 0; i < currentPointerCount; i++) {
3871 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003872 current.rawPointerData.pointers[i].id = id;
3873 current.rawPointerData.idToIndex[id] = i;
3874 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003875 }
3876 return;
3877 }
3878
3879 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003880 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003881 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003882 uint32_t id = last.rawPointerData.pointers[0].id;
3883 current.rawPointerData.pointers[0].id = id;
3884 current.rawPointerData.idToIndex[id] = 0;
3885 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003886 return;
3887 }
3888
3889 // General case.
3890 // We build a heap of squared euclidean distances between current and last pointers
3891 // associated with the current and last pointer indices. Then, we find the best
3892 // match (by distance) for each current pointer.
3893 // The pointers must have the same tool type but it is possible for them to
3894 // transition from hovering to touching or vice-versa while retaining the same id.
3895 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3896
3897 uint32_t heapSize = 0;
3898 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3899 currentPointerIndex++) {
3900 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3901 lastPointerIndex++) {
3902 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003903 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003904 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003905 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003906 if (currentPointer.toolType == lastPointer.toolType) {
3907 int64_t deltaX = currentPointer.x - lastPointer.x;
3908 int64_t deltaY = currentPointer.y - lastPointer.y;
3909
3910 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3911
3912 // Insert new element into the heap (sift up).
3913 heap[heapSize].currentPointerIndex = currentPointerIndex;
3914 heap[heapSize].lastPointerIndex = lastPointerIndex;
3915 heap[heapSize].distance = distance;
3916 heapSize += 1;
3917 }
3918 }
3919 }
3920
3921 // Heapify
3922 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3923 startIndex -= 1;
3924 for (uint32_t parentIndex = startIndex;;) {
3925 uint32_t childIndex = parentIndex * 2 + 1;
3926 if (childIndex >= heapSize) {
3927 break;
3928 }
3929
3930 if (childIndex + 1 < heapSize &&
3931 heap[childIndex + 1].distance < heap[childIndex].distance) {
3932 childIndex += 1;
3933 }
3934
3935 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3936 break;
3937 }
3938
3939 swap(heap[parentIndex], heap[childIndex]);
3940 parentIndex = childIndex;
3941 }
3942 }
3943
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003944 if (DEBUG_POINTER_ASSIGNMENT) {
3945 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3946 for (size_t i = 0; i < heapSize; i++) {
3947 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3948 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3949 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003950 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003951
3952 // Pull matches out by increasing order of distance.
3953 // To avoid reassigning pointers that have already been matched, the loop keeps track
3954 // of which last and current pointers have been matched using the matchedXXXBits variables.
3955 // It also tracks the used pointer id bits.
3956 BitSet32 matchedLastBits(0);
3957 BitSet32 matchedCurrentBits(0);
3958 BitSet32 usedIdBits(0);
3959 bool first = true;
3960 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3961 while (heapSize > 0) {
3962 if (first) {
3963 // The first time through the loop, we just consume the root element of
3964 // the heap (the one with smallest distance).
3965 first = false;
3966 } else {
3967 // Previous iterations consumed the root element of the heap.
3968 // Pop root element off of the heap (sift down).
3969 heap[0] = heap[heapSize];
3970 for (uint32_t parentIndex = 0;;) {
3971 uint32_t childIndex = parentIndex * 2 + 1;
3972 if (childIndex >= heapSize) {
3973 break;
3974 }
3975
3976 if (childIndex + 1 < heapSize &&
3977 heap[childIndex + 1].distance < heap[childIndex].distance) {
3978 childIndex += 1;
3979 }
3980
3981 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3982 break;
3983 }
3984
3985 swap(heap[parentIndex], heap[childIndex]);
3986 parentIndex = childIndex;
3987 }
3988
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003989 if (DEBUG_POINTER_ASSIGNMENT) {
3990 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3991 for (size_t j = 0; j < heapSize; j++) {
3992 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3993 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3994 heap[j].distance);
3995 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003996 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003997 }
3998
3999 heapSize -= 1;
4000
4001 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4002 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4003
4004 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4005 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4006
4007 matchedCurrentBits.markBit(currentPointerIndex);
4008 matchedLastBits.markBit(lastPointerIndex);
4009
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004010 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4011 current.rawPointerData.pointers[currentPointerIndex].id = id;
4012 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4013 current.rawPointerData.markIdBit(id,
4014 current.rawPointerData.isHovering(
4015 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004016 usedIdBits.markBit(id);
4017
Harry Cutts45483602022-08-24 14:36:48 +00004018 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4019 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4020 ", distance=%" PRIu64,
4021 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004022 break;
4023 }
4024 }
4025
4026 // Assign fresh ids to pointers that were not matched in the process.
4027 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4028 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4029 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4030
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004031 current.rawPointerData.pointers[currentPointerIndex].id = id;
4032 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4033 current.rawPointerData.markIdBit(id,
4034 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004035
Harry Cutts45483602022-08-24 14:36:48 +00004036 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4037 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4038 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004039 }
4040}
4041
4042int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4043 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4044 return AKEY_STATE_VIRTUAL;
4045 }
4046
4047 for (const VirtualKey& virtualKey : mVirtualKeys) {
4048 if (virtualKey.keyCode == keyCode) {
4049 return AKEY_STATE_UP;
4050 }
4051 }
4052
4053 return AKEY_STATE_UNKNOWN;
4054}
4055
4056int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4057 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4058 return AKEY_STATE_VIRTUAL;
4059 }
4060
4061 for (const VirtualKey& virtualKey : mVirtualKeys) {
4062 if (virtualKey.scanCode == scanCode) {
4063 return AKEY_STATE_UP;
4064 }
4065 }
4066
4067 return AKEY_STATE_UNKNOWN;
4068}
4069
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004070bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4071 const std::vector<int32_t>& keyCodes,
4072 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004073 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004074 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004075 if (virtualKey.keyCode == keyCodes[i]) {
4076 outFlags[i] = 1;
4077 }
4078 }
4079 }
4080
4081 return true;
4082}
4083
4084std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4085 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004086 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004087 return std::make_optional(mPointerController->getDisplayId());
4088 } else {
4089 return std::make_optional(mViewport.displayId);
4090 }
4091 }
4092 return std::nullopt;
4093}
4094
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004095} // namespace android