blob: 5be694f35f566c762081eb871bc3d7b3abcb2ca1 [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>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000024#include <input/PrintTools.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070026#include "CursorButtonAccumulator.h"
27#include "CursorScrollAccumulator.h"
28#include "TouchButtonAccumulator.h"
29#include "TouchCursorInputMapperCommon.h"
30
31namespace android {
32
33// --- Constants ---
34
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070035// Artificial latency on synthetic events created from stylus data without corresponding touch
36// data.
37static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
38
HQ Liue6983c72022-04-19 22:14:56 +000039// Minimum width between two pointers to determine a gesture as freeform gesture in mm
40static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070041// --- Static Definitions ---
42
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000043static const DisplayViewport kUninitializedViewport;
44
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070045template <typename T>
46inline static void swap(T& a, T& b) {
47 T temp = a;
48 a = b;
49 b = temp;
50}
51
52static float calculateCommonVector(float a, float b) {
53 if (a > 0 && b > 0) {
54 return a < b ? a : b;
55 } else if (a < 0 && b < 0) {
56 return a > b ? a : b;
57 } else {
58 return 0;
59 }
60}
61
62inline static float distance(float x1, float y1, float x2, float y2) {
63 return hypotf(x1 - x2, y1 - y2);
64}
65
66inline static int32_t signExtendNybble(int32_t value) {
67 return value >= 8 ? value - 16 : value;
68}
69
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070070// --- RawPointerData ---
71
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070072void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
73 float x = 0, y = 0;
74 uint32_t count = touchingIdBits.count();
75 if (count) {
76 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
77 uint32_t id = idBits.clearFirstMarkedBit();
78 const Pointer& pointer = pointerForId(id);
79 x += pointer.x;
80 y += pointer.y;
81 }
82 x /= count;
83 y /= count;
84 }
85 *outX = x;
86 *outY = y;
87}
88
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070089// --- TouchInputMapper ---
90
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -080091TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
92 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +000093 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070094 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +010095 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -070096 mDisplayWidth(-1),
97 mDisplayHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070098 mPhysicalWidth(-1),
99 mPhysicalHeight(-1),
100 mPhysicalLeft(0),
101 mPhysicalTop(0),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700102 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700103
104TouchInputMapper::~TouchInputMapper() {}
105
Philip Junker4af3b3d2021-12-14 10:36:55 +0100106uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700107 return mSource;
108}
109
110void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
111 InputMapper::populateDeviceInfo(info);
112
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000113 if (mDeviceMode == DeviceMode::DISABLED) {
114 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700115 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000116
117 info->addMotionRange(mOrientedRanges.x);
118 info->addMotionRange(mOrientedRanges.y);
119 info->addMotionRange(mOrientedRanges.pressure);
120
121 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
122 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
123 //
124 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
125 // motion, i.e. the hardware dimensions, as the finger could move completely across the
126 // touchpad in one sample cycle.
127 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
128 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
129 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
130 x.resolution);
131 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
132 y.resolution);
133 }
134
135 if (mOrientedRanges.size) {
136 info->addMotionRange(*mOrientedRanges.size);
137 }
138
139 if (mOrientedRanges.touchMajor) {
140 info->addMotionRange(*mOrientedRanges.touchMajor);
141 info->addMotionRange(*mOrientedRanges.touchMinor);
142 }
143
144 if (mOrientedRanges.toolMajor) {
145 info->addMotionRange(*mOrientedRanges.toolMajor);
146 info->addMotionRange(*mOrientedRanges.toolMinor);
147 }
148
149 if (mOrientedRanges.orientation) {
150 info->addMotionRange(*mOrientedRanges.orientation);
151 }
152
153 if (mOrientedRanges.distance) {
154 info->addMotionRange(*mOrientedRanges.distance);
155 }
156
157 if (mOrientedRanges.tilt) {
158 info->addMotionRange(*mOrientedRanges.tilt);
159 }
160
161 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
162 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
163 }
164 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
165 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
166 }
167 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
168 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
169 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
170 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
171 x.resolution);
172 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
173 y.resolution);
174 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
175 x.resolution);
176 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
177 y.resolution);
178 }
179 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000180 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700181}
182
183void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700184 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800185 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700186 dumpParameters(dump);
187 dumpVirtualKeys(dump);
188 dumpRawPointerAxes(dump);
189 dumpCalibration(dump);
190 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700191 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700192
193 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700194 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
195 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
196 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
197 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
198 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
199 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
200 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
201 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
202 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
203 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
204 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
205 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
206 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
207 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
208
209 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
210 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
211 mLastRawState.rawPointerData.pointerCount);
212 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
213 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
214 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
215 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
216 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
217 "toolType=%d, isHovering=%s\n",
218 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
219 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
220 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
221 pointer.distance, pointer.toolType, toString(pointer.isHovering));
222 }
223
224 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
225 mLastCookedState.buttonState);
226 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
227 mLastCookedState.cookedPointerData.pointerCount);
228 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
229 const PointerProperties& pointerProperties =
230 mLastCookedState.cookedPointerData.pointerProperties[i];
231 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000232 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
233 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
234 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700235 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
236 "toolType=%d, isHovering=%s\n",
237 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000238 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
239 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700240 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
241 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
242 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
243 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
244 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
245 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
246 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
247 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
248 pointerProperties.toolType,
249 toString(mLastCookedState.cookedPointerData.isHovering(i)));
250 }
251
252 dump += INDENT3 "Stylus Fusion:\n";
253 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
254 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000255 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
256 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700257 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
258 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000259 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
260 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700261 dump += INDENT3 "External Stylus State:\n";
262 dumpStylusState(dump, mExternalStylusState);
263
Michael Wright227c5542020-07-02 18:30:52 +0100264 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700265 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
266 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
267 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
268 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
269 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
270 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
271 }
272}
273
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700274std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
275 const InputReaderConfiguration* config,
276 uint32_t changes) {
277 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700278
279 mConfig = *config;
280
281 if (!changes) { // first time only
282 // Configure basic parameters.
283 configureParameters();
284
285 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800286 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000287 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700288
289 // Configure absolute axis information.
290 configureRawPointerAxes();
291
292 // Prepare input device calibration.
293 parseCalibration();
294 resolveCalibration();
295 }
296
297 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
298 // Update location calibration to reflect current settings
299 updateAffineTransformation();
300 }
301
302 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
303 // Update pointer speed.
304 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
305 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
306 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
307 }
308
309 bool resetNeeded = false;
310 if (!changes ||
311 (changes &
312 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800313 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
315 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
316 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700317 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700318 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700319 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700320 }
321
322 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700323 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000324
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700325 // Send reset, unless this is the first time the device has been configured,
326 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000327 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700328 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700329 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700330}
331
332void TouchInputMapper::resolveExternalStylusPresence() {
333 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800334 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700335 mExternalStylusConnected = !devices.empty();
336
337 if (!mExternalStylusConnected) {
338 resetExternalStylus();
339 }
340}
341
342void TouchInputMapper::configureParameters() {
343 // Use the pointer presentation mode for devices that do not support distinct
344 // multitouch. The spot-based presentation relies on being able to accurately
345 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800346 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100347 ? Parameters::GestureMode::SINGLE_TOUCH
348 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700349
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700350 std::string gestureModeString;
351 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800352 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700353 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100354 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100356 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700357 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700358 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700359 }
360 }
361
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800362 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700363 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100364 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800365 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700366 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100367 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700368 } else {
369 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100370 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700371 }
372
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800373 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700375 std::string deviceTypeString;
376 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800377 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700378 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100379 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700380 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100381 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700382 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100383 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700385 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700386 }
387 }
388
Michael Wright227c5542020-07-02 18:30:52 +0100389 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700390 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800391 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700392
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700393 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700394 std::string orientationString;
395 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700396 orientationString)) {
397 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
398 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
399 } else if (orientationString == "ORIENTATION_90") {
400 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
401 } else if (orientationString == "ORIENTATION_180") {
402 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
403 } else if (orientationString == "ORIENTATION_270") {
404 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
405 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700406 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700407 }
408 }
409
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700410 mParameters.hasAssociatedDisplay = false;
411 mParameters.associatedDisplayIsExternal = false;
412 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100413 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
414 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700415 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100416 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800417 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700418 std::string uniqueDisplayId;
419 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800420 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
422 }
423 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800424 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700425 mParameters.hasAssociatedDisplay = true;
426 }
427
428 // Initial downs on external touch devices should wake the device.
429 // Normally we don't do this for internal touch screens to prevent them from waking
430 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800431 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700432 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000433
434 mParameters.supportsUsi = false;
435 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
436 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700437
438 mParameters.enableForInactiveViewport = false;
439 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
440 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700441}
442
443void TouchInputMapper::dumpParameters(std::string& dump) {
444 dump += INDENT3 "Parameters:\n";
445
Dominik Laskowski75788452021-02-09 18:51:25 -0800446 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447
Dominik Laskowski75788452021-02-09 18:51:25 -0800448 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449
450 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
451 "displayId='%s'\n",
452 toString(mParameters.hasAssociatedDisplay),
453 toString(mParameters.associatedDisplayIsExternal),
454 mParameters.uniqueDisplayId.c_str());
455 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800456 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000457 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700458 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
459 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460}
461
462void TouchInputMapper::configureRawPointerAxes() {
463 mRawPointerAxes.clear();
464}
465
466void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
467 dump += INDENT3 "Raw Touch Axes:\n";
468 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
469 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
470 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
471 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
472 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
473 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
474 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
475 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
476 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
477 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
478 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
479 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
480 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
481}
482
483bool TouchInputMapper::hasExternalStylus() const {
484 return mExternalStylusConnected;
485}
486
487/**
488 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000489 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800490 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000491 * 3. Get the matching viewport by either unique id in idc file or by the display type
492 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800493 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700494 */
495std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800496 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000497 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800498 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700499 }
500
Christine Franks2a2293c2022-01-18 11:51:16 -0800501 const std::optional<std::string> associatedDisplayUniqueId =
502 getDeviceContext().getAssociatedDisplayUniqueId();
503 if (associatedDisplayUniqueId) {
504 return getDeviceContext().getAssociatedViewport();
505 }
506
Michael Wright227c5542020-07-02 18:30:52 +0100507 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800508 std::optional<DisplayViewport> viewport =
509 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
510 if (viewport) {
511 return viewport;
512 } else {
513 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
514 mConfig.defaultPointerDisplayId);
515 }
516 }
517
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700518 // Check if uniqueDisplayId is specified in idc file.
519 if (!mParameters.uniqueDisplayId.empty()) {
520 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
521 }
522
523 ViewportType viewportTypeToUse;
524 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100525 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700526 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100527 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700528 }
529
530 std::optional<DisplayViewport> viewport =
531 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100532 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700533 ALOGW("Input device %s should be associated with external display, "
534 "fallback to internal one for the external viewport is not found.",
535 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100536 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700537 }
538
539 return viewport;
540 }
541
542 // No associated display, return a non-display viewport.
543 DisplayViewport newViewport;
544 // Raw width and height in the natural orientation.
545 int32_t rawWidth = mRawPointerAxes.getRawWidth();
546 int32_t rawHeight = mRawPointerAxes.getRawHeight();
547 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
548 return std::make_optional(newViewport);
549}
550
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800551int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
552 if (resolution < 0) {
553 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
554 getDeviceName().c_str());
555 return 0;
556 }
557 return resolution;
558}
559
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800560void TouchInputMapper::initializeSizeRanges() {
561 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
562 mSizeScale = 0.0f;
563 return;
564 }
565
566 // Size of diagonal axis.
567 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
568
569 // Size factors.
570 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
571 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
572 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
573 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
574 } else {
575 mSizeScale = 0.0f;
576 }
577
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700578 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
579 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
580 .source = mSource,
581 .min = 0,
582 .max = diagonalSize,
583 .flat = 0,
584 .fuzz = 0,
585 .resolution = 0,
586 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800587
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800588 if (mRawPointerAxes.touchMajor.valid) {
589 mRawPointerAxes.touchMajor.resolution =
590 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700591 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800592 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800593
594 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700595 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800596 if (mRawPointerAxes.touchMinor.valid) {
597 mRawPointerAxes.touchMinor.resolution =
598 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700599 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800600 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800601
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700602 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
603 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
604 .source = mSource,
605 .min = 0,
606 .max = diagonalSize,
607 .flat = 0,
608 .fuzz = 0,
609 .resolution = 0,
610 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800611 if (mRawPointerAxes.toolMajor.valid) {
612 mRawPointerAxes.toolMajor.resolution =
613 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700614 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800615 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800616
617 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700618 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800619 if (mRawPointerAxes.toolMinor.valid) {
620 mRawPointerAxes.toolMinor.resolution =
621 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700622 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800623 }
624
625 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700626 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
627 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
628 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
629 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800630 } else {
631 // Support for other calibrations can be added here.
632 ALOGW("%s calibration is not supported for size ranges at the moment. "
633 "Using raw resolution instead",
634 ftl::enum_string(mCalibration.sizeCalibration).c_str());
635 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800636
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700637 mOrientedRanges.size = InputDeviceInfo::MotionRange{
638 .axis = AMOTION_EVENT_AXIS_SIZE,
639 .source = mSource,
640 .min = 0,
641 .max = 1.0,
642 .flat = 0,
643 .fuzz = 0,
644 .resolution = 0,
645 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800646}
647
648void TouchInputMapper::initializeOrientedRanges() {
649 // Configure X and Y factors.
650 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
651 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
652 mXPrecision = 1.0f / mXScale;
653 mYPrecision = 1.0f / mYScale;
654
655 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
656 mOrientedRanges.x.source = mSource;
657 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
658 mOrientedRanges.y.source = mSource;
659
660 // Scale factor for terms that are not oriented in a particular axis.
661 // If the pixels are square then xScale == yScale otherwise we fake it
662 // by choosing an average.
663 mGeometricScale = avg(mXScale, mYScale);
664
665 initializeSizeRanges();
666
667 // Pressure factors.
668 mPressureScale = 0;
669 float pressureMax = 1.0;
670 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
671 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700672 if (mCalibration.pressureScale) {
673 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800674 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
675 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
676 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
677 }
678 }
679
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700680 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
681 .axis = AMOTION_EVENT_AXIS_PRESSURE,
682 .source = mSource,
683 .min = 0,
684 .max = pressureMax,
685 .flat = 0,
686 .fuzz = 0,
687 .resolution = 0,
688 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800689
690 // Tilt
691 mTiltXCenter = 0;
692 mTiltXScale = 0;
693 mTiltYCenter = 0;
694 mTiltYScale = 0;
695 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
696 if (mHaveTilt) {
697 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
698 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
699 mTiltXScale = M_PI / 180;
700 mTiltYScale = M_PI / 180;
701
702 if (mRawPointerAxes.tiltX.resolution) {
703 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
704 }
705 if (mRawPointerAxes.tiltY.resolution) {
706 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
707 }
708
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700709 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
710 .axis = AMOTION_EVENT_AXIS_TILT,
711 .source = mSource,
712 .min = 0,
713 .max = M_PI_2,
714 .flat = 0,
715 .fuzz = 0,
716 .resolution = 0,
717 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800718 }
719
720 // Orientation
721 mOrientationScale = 0;
722 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700723 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
724 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
725 .source = mSource,
726 .min = -M_PI,
727 .max = M_PI,
728 .flat = 0,
729 .fuzz = 0,
730 .resolution = 0,
731 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800732
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800733 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
734 if (mCalibration.orientationCalibration ==
735 Calibration::OrientationCalibration::INTERPOLATED) {
736 if (mRawPointerAxes.orientation.valid) {
737 if (mRawPointerAxes.orientation.maxValue > 0) {
738 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
739 } else if (mRawPointerAxes.orientation.minValue < 0) {
740 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
741 } else {
742 mOrientationScale = 0;
743 }
744 }
745 }
746
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700747 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
748 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
749 .source = mSource,
750 .min = -M_PI_2,
751 .max = M_PI_2,
752 .flat = 0,
753 .fuzz = 0,
754 .resolution = 0,
755 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800756 }
757
758 // Distance
759 mDistanceScale = 0;
760 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
761 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700762 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800763 }
764
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700765 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800766
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700767 .axis = AMOTION_EVENT_AXIS_DISTANCE,
768 .source = mSource,
769 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
770 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
771 .flat = 0,
772 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
773 .resolution = 0,
774 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800775 }
776
777 // Compute oriented precision, scales and ranges.
778 // Note that the maximum value reported is an inclusive maximum value so it is one
779 // unit less than the total width or height of the display.
780 switch (mInputDeviceOrientation) {
781 case DISPLAY_ORIENTATION_90:
782 case DISPLAY_ORIENTATION_270:
783 mOrientedXPrecision = mYPrecision;
784 mOrientedYPrecision = mXPrecision;
785
786 mOrientedRanges.x.min = 0;
787 mOrientedRanges.x.max = mDisplayHeight - 1;
788 mOrientedRanges.x.flat = 0;
789 mOrientedRanges.x.fuzz = 0;
790 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
791
792 mOrientedRanges.y.min = 0;
793 mOrientedRanges.y.max = mDisplayWidth - 1;
794 mOrientedRanges.y.flat = 0;
795 mOrientedRanges.y.fuzz = 0;
796 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
797 break;
798
799 default:
800 mOrientedXPrecision = mXPrecision;
801 mOrientedYPrecision = mYPrecision;
802
803 mOrientedRanges.x.min = 0;
804 mOrientedRanges.x.max = mDisplayWidth - 1;
805 mOrientedRanges.x.flat = 0;
806 mOrientedRanges.x.fuzz = 0;
807 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
808
809 mOrientedRanges.y.min = 0;
810 mOrientedRanges.y.max = mDisplayHeight - 1;
811 mOrientedRanges.y.flat = 0;
812 mOrientedRanges.y.fuzz = 0;
813 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
814 break;
815 }
816}
817
Prabir Pradhan1728b212021-10-19 16:00:03 -0700818void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000819 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700820
821 resolveExternalStylusPresence();
822
823 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100824 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000825 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700826 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100827 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700828 if (hasStylus()) {
829 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000830 } else {
831 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700832 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800833 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700834 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100835 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700836 if (hasStylus()) {
837 mSource |= AINPUT_SOURCE_STYLUS;
838 }
839 if (hasExternalStylus()) {
840 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
841 }
Michael Wright227c5542020-07-02 18:30:52 +0100842 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700843 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100844 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700845 } else {
846 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100847 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700848 }
849
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000850 const std::optional<DisplayViewport> newViewportOpt = findViewport();
851
852 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700853 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
854 ALOGW("Touch device '%s' did not report support for X or Y axis! "
855 "The device will be inoperable.",
856 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100857 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000858 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700859 ALOGI("Touch device '%s' could not query the properties of its associated "
860 "display. The device will be inoperable until the display size "
861 "becomes available.",
862 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100863 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700864 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000865 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
866 getDeviceName().c_str(), getDeviceId());
867 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000868 }
869
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700870 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700871 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
872 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000873 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
874 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
875 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
876 const float rawMeanResolution =
877 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700878
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000879 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
880 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700881 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700882 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000883 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
884 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
885 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700886
Michael Wright227c5542020-07-02 18:30:52 +0100887 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700888 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700889 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
890 int32_t naturalPhysicalLeft, naturalPhysicalTop;
891 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700892
Prabir Pradhan1728b212021-10-19 16:00:03 -0700893 // Apply the inverse of the input device orientation so that the input device is
894 // configured in the same orientation as the viewport. The input device orientation will
895 // be re-applied by mInputDeviceOrientation.
896 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700897 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700898 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700899 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700900 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
901 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800902 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 naturalPhysicalTop = mViewport.physicalLeft;
904 naturalDeviceWidth = mViewport.deviceHeight;
905 naturalDeviceHeight = mViewport.deviceWidth;
906 break;
907 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700908 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
909 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
910 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
911 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
912 naturalDeviceWidth = mViewport.deviceWidth;
913 naturalDeviceHeight = mViewport.deviceHeight;
914 break;
915 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700916 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
917 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
918 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800919 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700920 naturalDeviceWidth = mViewport.deviceHeight;
921 naturalDeviceHeight = mViewport.deviceWidth;
922 break;
923 case DISPLAY_ORIENTATION_0:
924 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
926 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
927 naturalPhysicalLeft = mViewport.physicalLeft;
928 naturalPhysicalTop = mViewport.physicalTop;
929 naturalDeviceWidth = mViewport.deviceWidth;
930 naturalDeviceHeight = mViewport.deviceHeight;
931 break;
932 }
933
934 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
935 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
936 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
937 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
938 }
939
940 mPhysicalWidth = naturalPhysicalWidth;
941 mPhysicalHeight = naturalPhysicalHeight;
942 mPhysicalLeft = naturalPhysicalLeft;
943 mPhysicalTop = naturalPhysicalTop;
944
Prabir Pradhan1728b212021-10-19 16:00:03 -0700945 const int32_t oldDisplayWidth = mDisplayWidth;
946 const int32_t oldDisplayHeight = mDisplayHeight;
947 mDisplayWidth = naturalDeviceWidth;
948 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700949
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000950 // InputReader works in the un-rotated display coordinate space, so we don't need to do
951 // anything if the device is already orientation-aware. If the device is not
952 // orientation-aware, then we need to apply the inverse rotation of the display so that
953 // when the display rotation is applied later as a part of the per-window transform, we
954 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700955 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000956 ? DISPLAY_ORIENTATION_0
957 : getInverseRotation(mViewport.orientation);
958 // For orientation-aware devices that work in the un-rotated coordinate space, the
959 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000960 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
961 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
962 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700963
964 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700965 mInputDeviceOrientation =
966 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700967 } else {
968 mPhysicalWidth = rawWidth;
969 mPhysicalHeight = rawHeight;
970 mPhysicalLeft = 0;
971 mPhysicalTop = 0;
972
Prabir Pradhan1728b212021-10-19 16:00:03 -0700973 mDisplayWidth = rawWidth;
974 mDisplayHeight = rawHeight;
975 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700976 }
977 }
978
979 // If moving between pointer modes, need to reset some state.
980 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
981 if (deviceModeChanged) {
982 mOrientedRanges.clear();
983 }
984
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800985 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
986 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100987 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800988 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000989 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
990 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800991 if (mPointerController == nullptr) {
992 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700993 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000994 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800995 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
996 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700997 } else {
lilinnandef700b2022-06-17 19:32:01 +0800998 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
999 !mConfig.showTouches) {
1000 mPointerController->clearSpots();
1001 }
Michael Wright17db18e2020-06-26 20:51:44 +01001002 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001003 }
1004
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001005 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001006 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1007 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001008 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1009 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001010
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011 configureVirtualKeys();
1012
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001013 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001014
1015 // Location
1016 updateAffineTransformation();
1017
Michael Wright227c5542020-07-02 18:30:52 +01001018 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001019 // Compute pointer gesture detection parameters.
1020 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001021 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001022
1023 // Scale movements such that one whole swipe of the touch pad covers a
1024 // given area relative to the diagonal size of the display when no acceleration
1025 // is applied.
1026 // Assume that the touch pad has a square aspect ratio such that movements in
1027 // X and Y of the same number of raw units cover the same physical distance.
1028 mPointerXMovementScale =
1029 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1030 mPointerYMovementScale = mPointerXMovementScale;
1031
1032 // Scale zooms to cover a smaller range of the display than movements do.
1033 // This value determines the area around the pointer that is affected by freeform
1034 // pointer gestures.
1035 mPointerXZoomScale =
1036 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1037 mPointerYZoomScale = mPointerXZoomScale;
1038
HQ Liue6983c72022-04-19 22:14:56 +00001039 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1040 // axis is non positive value.
1041 const float minFreeformGestureWidth =
1042 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1043
1044 mPointerGestureMaxSwipeWidth =
1045 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1046 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001047 }
1048
1049 // Inform the dispatcher about the changes.
1050 *outResetNeeded = true;
1051 bumpGeneration();
1052 }
1053}
1054
Prabir Pradhan1728b212021-10-19 16:00:03 -07001055void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001056 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001057 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1058 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1060 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1061 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1062 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001063 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001064}
1065
1066void TouchInputMapper::configureVirtualKeys() {
1067 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001068 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001069
1070 mVirtualKeys.clear();
1071
1072 if (virtualKeyDefinitions.size() == 0) {
1073 return;
1074 }
1075
1076 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1077 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1078 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1079 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1080
1081 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1082 VirtualKey virtualKey;
1083
1084 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1085 int32_t keyCode;
1086 int32_t dummyKeyMetaState;
1087 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001088 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1089 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001090 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1091 continue; // drop the key
1092 }
1093
1094 virtualKey.keyCode = keyCode;
1095 virtualKey.flags = flags;
1096
1097 // convert the key definition's display coordinates into touch coordinates for a hit box
1098 int32_t halfWidth = virtualKeyDefinition.width / 2;
1099 int32_t halfHeight = virtualKeyDefinition.height / 2;
1100
1101 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001102 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001103 touchScreenLeft;
1104 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001105 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001106 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001107 virtualKey.hitTop =
1108 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001110 virtualKey.hitBottom =
1111 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112 touchScreenTop;
1113 mVirtualKeys.push_back(virtualKey);
1114 }
1115}
1116
1117void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1118 if (!mVirtualKeys.empty()) {
1119 dump += INDENT3 "Virtual Keys:\n";
1120
1121 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1122 const VirtualKey& virtualKey = mVirtualKeys[i];
1123 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1124 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1125 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1126 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1127 }
1128 }
1129}
1130
1131void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001132 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 Calibration& out = mCalibration;
1134
1135 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001137 std::string sizeCalibrationString;
1138 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001148 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001150 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 }
1152 }
1153
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001154 float sizeScale;
1155
1156 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1157 out.sizeScale = sizeScale;
1158 }
1159 float sizeBias;
1160 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1161 out.sizeBias = sizeBias;
1162 }
1163 bool sizeIsSummed;
1164 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1165 out.sizeIsSummed = sizeIsSummed;
1166 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167
1168 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001170 std::string pressureCalibrationString;
1171 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 } else if (pressureCalibrationString != "default") {
1179 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001180 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 }
1182 }
1183
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001184 float pressureScale;
1185 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1186 out.pressureScale = pressureScale;
1187 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188
1189 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001191 std::string orientationCalibrationString;
1192 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001194 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001198 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 } else if (orientationCalibrationString != "default") {
1200 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001201 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 }
1203 }
1204
1205 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001207 std::string distanceCalibrationString;
1208 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 } else if (distanceCalibrationString != "default") {
1214 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001215 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 }
1217 }
1218
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001219 float distanceScale;
1220 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1221 out.distanceScale = distanceScale;
1222 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001225 std::string coverageCalibrationString;
1226 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001228 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001230 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 } else if (coverageCalibrationString != "default") {
1232 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001233 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 }
1235 }
1236}
1237
1238void TouchInputMapper::resolveCalibration() {
1239 // Size
1240 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001241 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1242 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 }
1244 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001245 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247
1248 // Pressure
1249 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001250 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1251 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 }
1253 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001254 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256
1257 // Orientation
1258 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001259 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1260 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 }
1262 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001263 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265
1266 // Distance
1267 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001268 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1269 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270 }
1271 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001272 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 }
1274
1275 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001276 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1277 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 }
1279}
1280
1281void TouchInputMapper::dumpCalibration(std::string& dump) {
1282 dump += INDENT3 "Calibration:\n";
1283
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001284 dump += INDENT4 "touch.size.calibration: ";
1285 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001287 if (mCalibration.sizeScale) {
1288 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 }
1290
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001291 if (mCalibration.sizeBias) {
1292 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 }
1294
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001295 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001297 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 }
1299
1300 // Pressure
1301 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001302 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 dump += INDENT4 "touch.pressure.calibration: none\n";
1304 break;
Michael Wright227c5542020-07-02 18:30:52 +01001305 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 dump += INDENT4 "touch.pressure.calibration: physical\n";
1307 break;
Michael Wright227c5542020-07-02 18:30:52 +01001308 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1310 break;
1311 default:
1312 ALOG_ASSERT(false);
1313 }
1314
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001315 if (mCalibration.pressureScale) {
1316 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 }
1318
1319 // Orientation
1320 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001321 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += INDENT4 "touch.orientation.calibration: none\n";
1323 break;
Michael Wright227c5542020-07-02 18:30:52 +01001324 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1326 break;
Michael Wright227c5542020-07-02 18:30:52 +01001327 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.orientation.calibration: vector\n";
1329 break;
1330 default:
1331 ALOG_ASSERT(false);
1332 }
1333
1334 // Distance
1335 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001336 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 dump += INDENT4 "touch.distance.calibration: none\n";
1338 break;
Michael Wright227c5542020-07-02 18:30:52 +01001339 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340 dump += INDENT4 "touch.distance.calibration: scaled\n";
1341 break;
1342 default:
1343 ALOG_ASSERT(false);
1344 }
1345
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001346 if (mCalibration.distanceScale) {
1347 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001348 }
1349
1350 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001351 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001352 dump += INDENT4 "touch.coverage.calibration: none\n";
1353 break;
Michael Wright227c5542020-07-02 18:30:52 +01001354 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001355 dump += INDENT4 "touch.coverage.calibration: box\n";
1356 break;
1357 default:
1358 ALOG_ASSERT(false);
1359 }
1360}
1361
1362void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1363 dump += INDENT3 "Affine Transformation:\n";
1364
1365 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1366 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1367 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1368 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1369 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1370 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1371}
1372
1373void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001374 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001375 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001376}
1377
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001378std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001379 std::list<NotifyArgs> out = cancelTouch(when, when);
1380 updateTouchSpots();
1381
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001382 mCursorButtonAccumulator.reset(getDeviceContext());
1383 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001384 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001385
1386 mPointerVelocityControl.reset();
1387 mWheelXVelocityControl.reset();
1388 mWheelYVelocityControl.reset();
1389
1390 mRawStatesPending.clear();
1391 mCurrentRawState.clear();
1392 mCurrentCookedState.clear();
1393 mLastRawState.clear();
1394 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001395 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001396 mSentHoverEnter = false;
1397 mHavePointerIds = false;
1398 mCurrentMotionAborted = false;
1399 mDownTime = 0;
1400
1401 mCurrentVirtualKey.down = false;
1402
1403 mPointerGesture.reset();
1404 mPointerSimple.reset();
1405 resetExternalStylus();
1406
1407 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001408 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001409 mPointerController->clearSpots();
1410 }
1411
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001412 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001413}
1414
1415void TouchInputMapper::resetExternalStylus() {
1416 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001417 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001418 mExternalStylusFusionTimeout = LLONG_MAX;
1419 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001420 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001421}
1422
1423void TouchInputMapper::clearStylusDataPendingFlags() {
1424 mExternalStylusDataPending = false;
1425 mExternalStylusFusionTimeout = LLONG_MAX;
1426}
1427
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001428std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001429 mCursorButtonAccumulator.process(rawEvent);
1430 mCursorScrollAccumulator.process(rawEvent);
1431 mTouchButtonAccumulator.process(rawEvent);
1432
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001433 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001434 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001435 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001437 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438}
1439
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001440std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1441 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001442 if (mDeviceMode == DeviceMode::DISABLED) {
1443 // Only save the last pending state when the device is disabled.
1444 mRawStatesPending.clear();
1445 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446 // Push a new state.
1447 mRawStatesPending.emplace_back();
1448
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001449 RawState& next = mRawStatesPending.back();
1450 next.clear();
1451 next.when = when;
1452 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001453
1454 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001455 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1457
1458 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001459 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1460 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001461 mCursorScrollAccumulator.finishSync();
1462
1463 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001464 syncTouch(when, &next);
1465
1466 // The last RawState is the actually second to last, since we just added a new state
1467 const RawState& last =
1468 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001469
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001470 std::tie(next.when, next.readTime) =
1471 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1472 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001473
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001474 // Assign pointer ids.
1475 if (!mHavePointerIds) {
1476 assignPointerIds(last, next);
1477 }
1478
Harry Cutts45483602022-08-24 14:36:48 +00001479 ALOGD_IF(DEBUG_RAW_EVENTS,
1480 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1481 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1482 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1483 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1484 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1485 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001486
Arthur Hung9ad18942021-06-19 02:04:46 +00001487 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1488 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1489 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1490 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1491 next.rawPointerData.hoveringIdBits.value);
1492 }
1493
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001494 out += processRawTouches(false /*timeout*/);
1495 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496}
1497
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001498std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1499 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001500 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001501 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001502 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001503 }
1504
1505 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1506 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1507 // touching the current state will only observe the events that have been dispatched to the
1508 // rest of the pipeline.
1509 const size_t N = mRawStatesPending.size();
1510 size_t count;
1511 for (count = 0; count < N; count++) {
1512 const RawState& next = mRawStatesPending[count];
1513
1514 // A failure to assign the stylus id means that we're waiting on stylus data
1515 // and so should defer the rest of the pipeline.
1516 if (assignExternalStylusId(next, timeout)) {
1517 break;
1518 }
1519
1520 // All ready to go.
1521 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001522 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001523 if (mCurrentRawState.when < mLastRawState.when) {
1524 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001525 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001526 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001527 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001528 }
1529 if (count != 0) {
1530 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1531 }
1532
1533 if (mExternalStylusDataPending) {
1534 if (timeout) {
1535 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1536 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001537 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001538 ALOGD_IF(DEBUG_STYLUS_FUSION,
1539 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001540 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001541 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001542 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1543 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1544 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1545 }
1546 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001547 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001548}
1549
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001550std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1551 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001552 // Always start with a clean state.
1553 mCurrentCookedState.clear();
1554
1555 // Apply stylus buttons to current raw state.
1556 applyExternalStylusButtonState(when);
1557
1558 // Handle policy on initial down or hover events.
1559 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1560 mCurrentRawState.rawPointerData.pointerCount != 0;
1561
1562 uint32_t policyFlags = 0;
1563 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1564 if (initialDown || buttonsPressed) {
1565 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001566 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001567 getContext()->fadePointer();
1568 }
1569
1570 if (mParameters.wake) {
1571 policyFlags |= POLICY_FLAG_WAKE;
1572 }
1573 }
1574
1575 // Consume raw off-screen touches before cooking pointer data.
1576 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001577 bool consumed;
1578 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1579 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001580 mCurrentRawState.rawPointerData.clear();
1581 }
1582
1583 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1584 // with cooked pointer data that has the same ids and indices as the raw data.
1585 // The following code can use either the raw or cooked data, as needed.
1586 cookPointerData();
1587
1588 // Apply stylus pressure to current cooked state.
1589 applyExternalStylusTouchState(when);
1590
1591 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001592 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1593 mSource, mViewport.displayId, policyFlags,
1594 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001595
1596 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001597 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001598 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1599 uint32_t id = idBits.clearFirstMarkedBit();
1600 const RawPointerData::Pointer& pointer =
1601 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001602 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001603 mCurrentCookedState.stylusIdBits.markBit(id);
1604 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1605 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1606 mCurrentCookedState.fingerIdBits.markBit(id);
1607 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1608 mCurrentCookedState.mouseIdBits.markBit(id);
1609 }
1610 }
1611 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1612 uint32_t id = idBits.clearFirstMarkedBit();
1613 const RawPointerData::Pointer& pointer =
1614 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001615 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 mCurrentCookedState.stylusIdBits.markBit(id);
1617 }
1618 }
1619
1620 // Stylus takes precedence over all tools, then mouse, then finger.
1621 PointerUsage pointerUsage = mPointerUsage;
1622 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1623 mCurrentCookedState.mouseIdBits.clear();
1624 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001625 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1627 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001628 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1630 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001631 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 }
1633
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001634 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001635 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001637 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001638 out += dispatchButtonRelease(when, readTime, policyFlags);
1639 out += dispatchHoverExit(when, readTime, policyFlags);
1640 out += dispatchTouches(when, readTime, policyFlags);
1641 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1642 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001643 }
1644
1645 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1646 mCurrentMotionAborted = false;
1647 }
1648 }
1649
1650 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001651 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1652 mSource, mViewport.displayId, policyFlags,
1653 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001654
1655 // Clear some transient state.
1656 mCurrentRawState.rawVScroll = 0;
1657 mCurrentRawState.rawHScroll = 0;
1658
1659 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001660 mLastRawState = mCurrentRawState;
1661 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001662 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001663}
1664
Garfield Tanc734e4f2021-01-15 20:01:39 -08001665void TouchInputMapper::updateTouchSpots() {
1666 if (!mConfig.showTouches || mPointerController == nullptr) {
1667 return;
1668 }
1669
1670 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1671 // clear touch spots.
1672 if (mDeviceMode != DeviceMode::DIRECT &&
1673 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1674 return;
1675 }
1676
1677 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1678 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1679
1680 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001681 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1682 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001683 mCurrentCookedState.cookedPointerData.touchingIdBits,
1684 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001685}
1686
1687bool TouchInputMapper::isTouchScreen() {
1688 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1689 mParameters.hasAssociatedDisplay;
1690}
1691
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001692void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001693 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1694 // If any of the external buttons are already pressed by the touch device, ignore them.
1695 const int32_t pressedButtons = ~mCurrentRawState.buttonState & mExternalStylusState.buttons;
1696 const int32_t releasedButtons =
1697 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1698
1699 mCurrentRawState.buttonState |= pressedButtons;
1700 mCurrentRawState.buttonState &= ~releasedButtons;
1701
1702 mExternalStylusButtonsApplied |= pressedButtons;
1703 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001704 }
1705}
1706
1707void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1708 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1709 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001710 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1711 return;
1712 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001713
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001714 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1715 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1716 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1717 : 0.f;
1718 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1719 pressure = *mExternalStylusState.pressure;
1720 }
1721 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1722 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001723
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001724 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001725 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001726 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001727 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001728 }
1729}
1730
1731bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001732 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001733 return false;
1734 }
1735
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001736 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001737 if (mFusedStylusPointerId &&
1738 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001739 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001740 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001741 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001742 }
1743
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001744 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1745 state.rawPointerData.pointerCount != 0;
1746 if (!initialDown) {
1747 return false;
1748 }
1749
1750 if (!mExternalStylusState.pressure) {
1751 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1752 return false;
1753 }
1754
1755 if (*mExternalStylusState.pressure != 0.0f) {
1756 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1757 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1758 return false;
1759 }
1760
1761 if (timeout) {
1762 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1763 mFusedStylusPointerId.reset();
1764 mExternalStylusFusionTimeout = LLONG_MAX;
1765 return false;
1766 }
1767
1768 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1769 // being processed until we either get pressure data or timeout.
1770 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1771 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1772 }
1773 ALOGD_IF(DEBUG_STYLUS_FUSION,
1774 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1775 mExternalStylusFusionTimeout);
1776 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1777 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001778}
1779
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001780std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1781 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001782 if (mDeviceMode == DeviceMode::POINTER) {
1783 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001784 // Since this is a synthetic event, we can consider its latency to be zero
1785 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001786 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001787 }
Michael Wright227c5542020-07-02 18:30:52 +01001788 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001789 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001790 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001791 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1792 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1793 }
1794 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001795 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001796}
1797
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001798std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1799 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001800 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001801 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001802 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001803 // The following three cases are handled here:
1804 // - We're in the middle of a fused stream of data;
1805 // - We're waiting on external stylus data before dispatching the initial down; or
1806 // - Only the button state, which is not reported through a specific pointer, has changed.
1807 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001808 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001809 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001810 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001811 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001812}
1813
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001814std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1815 uint32_t policyFlags, bool& outConsumed) {
1816 outConsumed = false;
1817 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001818 // Check for release of a virtual key.
1819 if (mCurrentVirtualKey.down) {
1820 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1821 // Pointer went up while virtual key was down.
1822 mCurrentVirtualKey.down = false;
1823 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001824 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1825 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1826 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001827 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1828 AKEY_EVENT_FLAG_FROM_SYSTEM |
1829 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001830 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001831 outConsumed = true;
1832 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001833 }
1834
1835 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1836 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1837 const RawPointerData::Pointer& pointer =
1838 mCurrentRawState.rawPointerData.pointerForId(id);
1839 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1840 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1841 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001842 outConsumed = true;
1843 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001844 }
1845 }
1846
1847 // Pointer left virtual key area or another pointer also went down.
1848 // Send key cancellation but do not consume the touch yet.
1849 // This is useful when the user swipes through from the virtual key area
1850 // into the main display surface.
1851 mCurrentVirtualKey.down = false;
1852 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001853 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1854 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001855 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1856 AKEY_EVENT_FLAG_FROM_SYSTEM |
1857 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1858 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001859 }
1860 }
1861
1862 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1863 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1864 // Pointer just went down. Check for virtual key press or off-screen touches.
1865 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1866 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001867 // Skip checking whether the pointer is inside the physical frame if the device is in
1868 // unscaled mode.
1869 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1870 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001871 // If exactly one pointer went down, check for virtual key hit.
1872 // Otherwise we will drop the entire stroke.
1873 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1874 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1875 if (virtualKey) {
1876 mCurrentVirtualKey.down = true;
1877 mCurrentVirtualKey.downTime = when;
1878 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1879 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1880 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001881 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1882 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001883
1884 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001885 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1886 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1887 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001888 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1889 AKEY_EVENT_ACTION_DOWN,
1890 AKEY_EVENT_FLAG_FROM_SYSTEM |
1891 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001892 }
1893 }
1894 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001895 outConsumed = true;
1896 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001897 }
1898 }
1899
1900 // Disable all virtual key touches that happen within a short time interval of the
1901 // most recent touch within the screen area. The idea is to filter out stray
1902 // virtual key presses when interacting with the touch screen.
1903 //
1904 // Problems we're trying to solve:
1905 //
1906 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1907 // virtual key area that is implemented by a separate touch panel and accidentally
1908 // triggers a virtual key.
1909 //
1910 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1911 // area and accidentally triggers a virtual key. This often happens when virtual keys
1912 // are layed out below the screen near to where the on screen keyboard's space bar
1913 // is displayed.
1914 if (mConfig.virtualKeyQuietTime > 0 &&
1915 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001916 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001917 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001918 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001919}
1920
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001921NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1922 uint32_t policyFlags, int32_t keyEventAction,
1923 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924 int32_t keyCode = mCurrentVirtualKey.keyCode;
1925 int32_t scanCode = mCurrentVirtualKey.scanCode;
1926 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001927 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001928 policyFlags |= POLICY_FLAG_VIRTUAL;
1929
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001930 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1931 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1932 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001933}
1934
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001935std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1936 uint32_t policyFlags) {
1937 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001938 if (mCurrentMotionAborted) {
1939 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001940 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001941 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001942 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1943 if (!currentIdBits.isEmpty()) {
1944 int32_t metaState = getContext()->getGlobalMetaState();
1945 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001946 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001947 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1948 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001949 mCurrentCookedState.cookedPointerData.pointerProperties,
1950 mCurrentCookedState.cookedPointerData.pointerCoords,
1951 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1952 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1953 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001954 mCurrentMotionAborted = true;
1955 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001956 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001957}
1958
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001959// Updates pointer coords and properties for pointers with specified ids that have moved.
1960// Returns true if any of them changed.
1961static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1962 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1963 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1964 BitSet32 idBits) {
1965 bool changed = false;
1966 while (!idBits.isEmpty()) {
1967 uint32_t id = idBits.clearFirstMarkedBit();
1968 uint32_t inIndex = inIdToIndex[id];
1969 uint32_t outIndex = outIdToIndex[id];
1970
1971 const PointerProperties& curInProperties = inProperties[inIndex];
1972 const PointerCoords& curInCoords = inCoords[inIndex];
1973 PointerProperties& curOutProperties = outProperties[outIndex];
1974 PointerCoords& curOutCoords = outCoords[outIndex];
1975
1976 if (curInProperties != curOutProperties) {
1977 curOutProperties.copyFrom(curInProperties);
1978 changed = true;
1979 }
1980
1981 if (curInCoords != curOutCoords) {
1982 curOutCoords.copyFrom(curInCoords);
1983 changed = true;
1984 }
1985 }
1986 return changed;
1987}
1988
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001989std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1990 uint32_t policyFlags) {
1991 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001992 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1993 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1994 int32_t metaState = getContext()->getGlobalMetaState();
1995 int32_t buttonState = mCurrentCookedState.buttonState;
1996
1997 if (currentIdBits == lastIdBits) {
1998 if (!currentIdBits.isEmpty()) {
1999 // No pointer id changes so this is a move event.
2000 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002001 out.push_back(
2002 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2003 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2004 mCurrentCookedState.cookedPointerData.pointerProperties,
2005 mCurrentCookedState.cookedPointerData.pointerCoords,
2006 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2007 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2008 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002009 }
2010 } else {
2011 // There may be pointers going up and pointers going down and pointers moving
2012 // all at the same time.
2013 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2014 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2015 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2016 BitSet32 dispatchedIdBits(lastIdBits.value);
2017
2018 // Update last coordinates of pointers that have moved so that we observe the new
2019 // pointer positions at the same time as other pointers that have just gone up.
2020 bool moveNeeded =
2021 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2022 mCurrentCookedState.cookedPointerData.pointerCoords,
2023 mCurrentCookedState.cookedPointerData.idToIndex,
2024 mLastCookedState.cookedPointerData.pointerProperties,
2025 mLastCookedState.cookedPointerData.pointerCoords,
2026 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2027 if (buttonState != mLastCookedState.buttonState) {
2028 moveNeeded = true;
2029 }
2030
2031 // Dispatch pointer up events.
2032 while (!upIdBits.isEmpty()) {
2033 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002034 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002035 if (isCanceled) {
2036 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2037 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002038 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2039 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2040 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2041 buttonState, 0,
2042 mLastCookedState.cookedPointerData.pointerProperties,
2043 mLastCookedState.cookedPointerData.pointerCoords,
2044 mLastCookedState.cookedPointerData.idToIndex,
2045 dispatchedIdBits, upId, mOrientedXPrecision,
2046 mOrientedYPrecision, mDownTime,
2047 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002048 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002049 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002050 }
2051
2052 // Dispatch move events if any of the remaining pointers moved from their old locations.
2053 // Although applications receive new locations as part of individual pointer up
2054 // events, they do not generally handle them except when presented in a move event.
2055 if (moveNeeded && !moveIdBits.isEmpty()) {
2056 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002057 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2058 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2059 mCurrentCookedState.cookedPointerData.pointerProperties,
2060 mCurrentCookedState.cookedPointerData.pointerCoords,
2061 mCurrentCookedState.cookedPointerData.idToIndex,
2062 dispatchedIdBits, -1, mOrientedXPrecision,
2063 mOrientedYPrecision, mDownTime,
2064 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002065 }
2066
2067 // Dispatch pointer down events using the new pointer locations.
2068 while (!downIdBits.isEmpty()) {
2069 uint32_t downId = downIdBits.clearFirstMarkedBit();
2070 dispatchedIdBits.markBit(downId);
2071
2072 if (dispatchedIdBits.count() == 1) {
2073 // First pointer is going down. Set down time.
2074 mDownTime = when;
2075 }
2076
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002077 out.push_back(
2078 dispatchMotion(when, readTime, policyFlags, mSource,
2079 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2080 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2081 mCurrentCookedState.cookedPointerData.pointerCoords,
2082 mCurrentCookedState.cookedPointerData.idToIndex,
2083 dispatchedIdBits, downId, mOrientedXPrecision,
2084 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002085 }
2086 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002087 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002088}
2089
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002090std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2091 uint32_t policyFlags) {
2092 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002093 if (mSentHoverEnter &&
2094 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2095 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2096 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002097 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2098 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2099 mLastCookedState.buttonState, 0,
2100 mLastCookedState.cookedPointerData.pointerProperties,
2101 mLastCookedState.cookedPointerData.pointerCoords,
2102 mLastCookedState.cookedPointerData.idToIndex,
2103 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2104 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2105 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002106 mSentHoverEnter = false;
2107 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002108 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002109}
2110
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002111std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2112 uint32_t policyFlags) {
2113 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002114 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2115 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2116 int32_t metaState = getContext()->getGlobalMetaState();
2117 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002118 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2119 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2120 mCurrentRawState.buttonState, 0,
2121 mCurrentCookedState.cookedPointerData.pointerProperties,
2122 mCurrentCookedState.cookedPointerData.pointerCoords,
2123 mCurrentCookedState.cookedPointerData.idToIndex,
2124 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2125 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2126 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002127 mSentHoverEnter = true;
2128 }
2129
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002130 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2131 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2132 mCurrentRawState.buttonState, 0,
2133 mCurrentCookedState.cookedPointerData.pointerProperties,
2134 mCurrentCookedState.cookedPointerData.pointerCoords,
2135 mCurrentCookedState.cookedPointerData.idToIndex,
2136 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2137 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2138 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002139 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002140 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141}
2142
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002143std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2144 uint32_t policyFlags) {
2145 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002146 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2147 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2148 const int32_t metaState = getContext()->getGlobalMetaState();
2149 int32_t buttonState = mLastCookedState.buttonState;
2150 while (!releasedButtons.isEmpty()) {
2151 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2152 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002153 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2154 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2155 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002156 mLastCookedState.cookedPointerData.pointerProperties,
2157 mLastCookedState.cookedPointerData.pointerCoords,
2158 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002159 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2160 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002161 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002162 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163}
2164
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002165std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2166 uint32_t policyFlags) {
2167 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002168 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2169 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2170 const int32_t metaState = getContext()->getGlobalMetaState();
2171 int32_t buttonState = mLastCookedState.buttonState;
2172 while (!pressedButtons.isEmpty()) {
2173 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2174 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002175 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2176 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2177 buttonState, 0,
2178 mCurrentCookedState.cookedPointerData.pointerProperties,
2179 mCurrentCookedState.cookedPointerData.pointerCoords,
2180 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2181 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2182 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002183 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002184 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185}
2186
2187const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2188 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2189 return cookedPointerData.touchingIdBits;
2190 }
2191 return cookedPointerData.hoveringIdBits;
2192}
2193
2194void TouchInputMapper::cookPointerData() {
2195 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2196
2197 mCurrentCookedState.cookedPointerData.clear();
2198 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2199 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2200 mCurrentRawState.rawPointerData.hoveringIdBits;
2201 mCurrentCookedState.cookedPointerData.touchingIdBits =
2202 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002203 mCurrentCookedState.cookedPointerData.canceledIdBits =
2204 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002205
2206 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2207 mCurrentCookedState.buttonState = 0;
2208 } else {
2209 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2210 }
2211
2212 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002213 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002214 for (uint32_t i = 0; i < currentPointerCount; i++) {
2215 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2216
2217 // Size
2218 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2219 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002220 case Calibration::SizeCalibration::GEOMETRIC:
2221 case Calibration::SizeCalibration::DIAMETER:
2222 case Calibration::SizeCalibration::BOX:
2223 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002224 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2225 touchMajor = in.touchMajor;
2226 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2227 toolMajor = in.toolMajor;
2228 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2229 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2230 : in.touchMajor;
2231 } else if (mRawPointerAxes.touchMajor.valid) {
2232 toolMajor = touchMajor = in.touchMajor;
2233 toolMinor = touchMinor =
2234 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2235 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2236 : in.touchMajor;
2237 } else if (mRawPointerAxes.toolMajor.valid) {
2238 touchMajor = toolMajor = in.toolMajor;
2239 touchMinor = toolMinor =
2240 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2241 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2242 : in.toolMajor;
2243 } else {
2244 ALOG_ASSERT(false,
2245 "No touch or tool axes. "
2246 "Size calibration should have been resolved to NONE.");
2247 touchMajor = 0;
2248 touchMinor = 0;
2249 toolMajor = 0;
2250 toolMinor = 0;
2251 size = 0;
2252 }
2253
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002254 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002255 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2256 if (touchingCount > 1) {
2257 touchMajor /= touchingCount;
2258 touchMinor /= touchingCount;
2259 toolMajor /= touchingCount;
2260 toolMinor /= touchingCount;
2261 size /= touchingCount;
2262 }
2263 }
2264
Michael Wright227c5542020-07-02 18:30:52 +01002265 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002266 touchMajor *= mGeometricScale;
2267 touchMinor *= mGeometricScale;
2268 toolMajor *= mGeometricScale;
2269 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002270 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002271 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2272 touchMinor = touchMajor;
2273 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2274 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002275 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002276 touchMinor = touchMajor;
2277 toolMinor = toolMajor;
2278 }
2279
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002280 mCalibration.applySizeScaleAndBias(touchMajor);
2281 mCalibration.applySizeScaleAndBias(touchMinor);
2282 mCalibration.applySizeScaleAndBias(toolMajor);
2283 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002284 size *= mSizeScale;
2285 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002286 case Calibration::SizeCalibration::DEFAULT:
2287 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2288 break;
2289 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002290 touchMajor = 0;
2291 touchMinor = 0;
2292 toolMajor = 0;
2293 toolMinor = 0;
2294 size = 0;
2295 break;
2296 }
2297
2298 // Pressure
2299 float pressure;
2300 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002301 case Calibration::PressureCalibration::PHYSICAL:
2302 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 pressure = in.pressure * mPressureScale;
2304 break;
2305 default:
2306 pressure = in.isHovering ? 0 : 1;
2307 break;
2308 }
2309
2310 // Tilt and Orientation
2311 float tilt;
2312 float orientation;
2313 if (mHaveTilt) {
2314 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2315 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2316 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2317 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2318 } else {
2319 tilt = 0;
2320
2321 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002322 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323 orientation = in.orientation * mOrientationScale;
2324 break;
Michael Wright227c5542020-07-02 18:30:52 +01002325 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002326 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2327 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2328 if (c1 != 0 || c2 != 0) {
2329 orientation = atan2f(c1, c2) * 0.5f;
2330 float confidence = hypotf(c1, c2);
2331 float scale = 1.0f + confidence / 16.0f;
2332 touchMajor *= scale;
2333 touchMinor /= scale;
2334 toolMajor *= scale;
2335 toolMinor /= scale;
2336 } else {
2337 orientation = 0;
2338 }
2339 break;
2340 }
2341 default:
2342 orientation = 0;
2343 }
2344 }
2345
2346 // Distance
2347 float distance;
2348 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002349 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002350 distance = in.distance * mDistanceScale;
2351 break;
2352 default:
2353 distance = 0;
2354 }
2355
2356 // Coverage
2357 int32_t rawLeft, rawTop, rawRight, rawBottom;
2358 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002359 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002360 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2361 rawRight = in.toolMinor & 0x0000ffff;
2362 rawBottom = in.toolMajor & 0x0000ffff;
2363 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2364 break;
2365 default:
2366 rawLeft = rawTop = rawRight = rawBottom = 0;
2367 break;
2368 }
2369
2370 // Adjust X,Y coords for device calibration
2371 // TODO: Adjust coverage coords?
2372 float xTransformed = in.x, yTransformed = in.y;
2373 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002374 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375
Prabir Pradhan1728b212021-10-19 16:00:03 -07002376 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 float left, top, right, bottom;
2378
Prabir Pradhan1728b212021-10-19 16:00:03 -07002379 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002381 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2382 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2383 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2384 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002386 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002388 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 }
2390 break;
2391 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2393 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002394 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2395 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002397 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002399 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400 }
2401 break;
2402 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2404 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002405 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2406 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002407 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002408 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002410 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 }
2412 break;
2413 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002414 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2415 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2416 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2417 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 break;
2419 }
2420
2421 // Write output coords.
2422 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2423 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002424 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2425 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2427 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2428 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2429 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2430 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2431 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2432 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002433 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2435 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2436 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2437 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2438 } else {
2439 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2440 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2441 }
2442
Chris Ye364fdb52020-08-05 15:07:56 -07002443 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002444 uint32_t id = in.id;
2445 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2446 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2447 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2448 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2449 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2450 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2451 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2452 }
2453
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454 // Write output properties.
2455 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 properties.clear();
2457 properties.id = id;
2458 properties.toolType = in.toolType;
2459
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002460 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002462 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 }
2464}
2465
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002466std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2467 uint32_t policyFlags,
2468 PointerUsage pointerUsage) {
2469 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002471 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 mPointerUsage = pointerUsage;
2473 }
2474
2475 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002476 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002477 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 break;
Michael Wright227c5542020-07-02 18:30:52 +01002479 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002480 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002481 break;
Michael Wright227c5542020-07-02 18:30:52 +01002482 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002483 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002484 break;
Michael Wright227c5542020-07-02 18:30:52 +01002485 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 break;
2487 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002488 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002489}
2490
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002491std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2492 uint32_t policyFlags) {
2493 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002495 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002496 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497 break;
Michael Wright227c5542020-07-02 18:30:52 +01002498 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002499 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002500 break;
Michael Wright227c5542020-07-02 18:30:52 +01002501 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002502 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 break;
Michael Wright227c5542020-07-02 18:30:52 +01002504 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002505 break;
2506 }
2507
Michael Wright227c5542020-07-02 18:30:52 +01002508 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002509 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002510}
2511
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002512std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2513 uint32_t policyFlags,
2514 bool isTimeout) {
2515 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516 // Update current gesture coordinates.
2517 bool cancelPreviousGesture, finishPreviousGesture;
2518 bool sendEvents =
2519 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2520 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002521 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 }
2523 if (finishPreviousGesture) {
2524 cancelPreviousGesture = false;
2525 }
2526
2527 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002528 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002529 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002530 if (finishPreviousGesture || cancelPreviousGesture) {
2531 mPointerController->clearSpots();
2532 }
2533
Michael Wright227c5542020-07-02 18:30:52 +01002534 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002535 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2536 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002537 mPointerGesture.currentGestureIdBits,
2538 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002539 }
2540 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002541 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002542 }
2543
2544 // Show or hide the pointer if needed.
2545 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002546 case PointerGesture::Mode::NEUTRAL:
2547 case PointerGesture::Mode::QUIET:
2548 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2549 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002550 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002551 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552 }
2553 break;
Michael Wright227c5542020-07-02 18:30:52 +01002554 case PointerGesture::Mode::TAP:
2555 case PointerGesture::Mode::TAP_DRAG:
2556 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2557 case PointerGesture::Mode::HOVER:
2558 case PointerGesture::Mode::PRESS:
2559 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002560 // Unfade the pointer when the current gesture manipulates the
2561 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002562 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002563 break;
Michael Wright227c5542020-07-02 18:30:52 +01002564 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002565 // Fade the pointer when the current gesture manipulates a different
2566 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002567 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002568 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002569 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002570 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002571 }
2572 break;
2573 }
2574
2575 // Send events!
2576 int32_t metaState = getContext()->getGlobalMetaState();
2577 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002578 const MotionClassification classification =
2579 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2580 ? MotionClassification::TWO_FINGER_SWIPE
2581 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002582
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002583 uint32_t flags = 0;
2584
2585 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2586 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2587 }
2588
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002589 // Update last coordinates of pointers that have moved so that we observe the new
2590 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002591 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2592 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2593 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2594 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2595 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2596 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002597 bool moveNeeded = false;
2598 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2599 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2600 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2601 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2602 mPointerGesture.lastGestureIdBits.value);
2603 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2604 mPointerGesture.currentGestureCoords,
2605 mPointerGesture.currentGestureIdToIndex,
2606 mPointerGesture.lastGestureProperties,
2607 mPointerGesture.lastGestureCoords,
2608 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2609 if (buttonState != mLastCookedState.buttonState) {
2610 moveNeeded = true;
2611 }
2612 }
2613
2614 // Send motion events for all pointers that went up or were canceled.
2615 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2616 if (!dispatchedGestureIdBits.isEmpty()) {
2617 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002618 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002619 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002620 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002621 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2622 mPointerGesture.lastGestureProperties,
2623 mPointerGesture.lastGestureCoords,
2624 mPointerGesture.lastGestureIdToIndex,
2625 dispatchedGestureIdBits, -1, 0, 0,
2626 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002627
2628 dispatchedGestureIdBits.clear();
2629 } else {
2630 BitSet32 upGestureIdBits;
2631 if (finishPreviousGesture) {
2632 upGestureIdBits = dispatchedGestureIdBits;
2633 } else {
2634 upGestureIdBits.value =
2635 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2636 }
2637 while (!upGestureIdBits.isEmpty()) {
2638 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2639
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002640 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2641 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2642 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2643 mPointerGesture.lastGestureProperties,
2644 mPointerGesture.lastGestureCoords,
2645 mPointerGesture.lastGestureIdToIndex,
2646 dispatchedGestureIdBits, id, 0, 0,
2647 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002648
2649 dispatchedGestureIdBits.clearBit(id);
2650 }
2651 }
2652 }
2653
2654 // Send motion events for all pointers that moved.
2655 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002656 out.push_back(
2657 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2658 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2659 mPointerGesture.currentGestureProperties,
2660 mPointerGesture.currentGestureCoords,
2661 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2662 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002663 }
2664
2665 // Send motion events for all pointers that went down.
2666 if (down) {
2667 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2668 ~dispatchedGestureIdBits.value);
2669 while (!downGestureIdBits.isEmpty()) {
2670 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2671 dispatchedGestureIdBits.markBit(id);
2672
2673 if (dispatchedGestureIdBits.count() == 1) {
2674 mPointerGesture.downTime = when;
2675 }
2676
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002677 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2678 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2679 buttonState, 0, mPointerGesture.currentGestureProperties,
2680 mPointerGesture.currentGestureCoords,
2681 mPointerGesture.currentGestureIdToIndex,
2682 dispatchedGestureIdBits, id, 0, 0,
2683 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002684 }
2685 }
2686
2687 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002688 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002689 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2690 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2691 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2692 mPointerGesture.currentGestureProperties,
2693 mPointerGesture.currentGestureCoords,
2694 mPointerGesture.currentGestureIdToIndex,
2695 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2696 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002697 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2698 // Synthesize a hover move event after all pointers go up to indicate that
2699 // the pointer is hovering again even if the user is not currently touching
2700 // the touch pad. This ensures that a view will receive a fresh hover enter
2701 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002702 float x, y;
2703 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002704
2705 PointerProperties pointerProperties;
2706 pointerProperties.clear();
2707 pointerProperties.id = 0;
2708 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2709
2710 PointerCoords pointerCoords;
2711 pointerCoords.clear();
2712 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2713 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2714
2715 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002716 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2717 mSource, displayId, policyFlags,
2718 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2719 buttonState, MotionClassification::NONE,
2720 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2721 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2722 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002723 }
2724
2725 // Update state.
2726 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2727 if (!down) {
2728 mPointerGesture.lastGestureIdBits.clear();
2729 } else {
2730 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2731 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2732 uint32_t id = idBits.clearFirstMarkedBit();
2733 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2734 mPointerGesture.lastGestureProperties[index].copyFrom(
2735 mPointerGesture.currentGestureProperties[index]);
2736 mPointerGesture.lastGestureCoords[index].copyFrom(
2737 mPointerGesture.currentGestureCoords[index]);
2738 mPointerGesture.lastGestureIdToIndex[id] = index;
2739 }
2740 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002741 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002742}
2743
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002744std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2745 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002746 const MotionClassification classification =
2747 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2748 ? MotionClassification::TWO_FINGER_SWIPE
2749 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002750 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002751 // Cancel previously dispatches pointers.
2752 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2753 int32_t metaState = getContext()->getGlobalMetaState();
2754 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002755 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002756 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2757 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002758 mPointerGesture.lastGestureProperties,
2759 mPointerGesture.lastGestureCoords,
2760 mPointerGesture.lastGestureIdToIndex,
2761 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2762 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002763 }
2764
2765 // Reset the current pointer gesture.
2766 mPointerGesture.reset();
2767 mPointerVelocityControl.reset();
2768
2769 // Remove any current spots.
2770 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002771 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002772 mPointerController->clearSpots();
2773 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002774 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002775}
2776
2777bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2778 bool* outFinishPreviousGesture, bool isTimeout) {
2779 *outCancelPreviousGesture = false;
2780 *outFinishPreviousGesture = false;
2781
2782 // Handle TAP timeout.
2783 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002784 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002785
Michael Wright227c5542020-07-02 18:30:52 +01002786 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2788 // The tap/drag timeout has not yet expired.
2789 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2790 mConfig.pointerGestureTapDragInterval);
2791 } else {
2792 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002793 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 *outFinishPreviousGesture = true;
2795
2796 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002797 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002798 mPointerGesture.currentGestureIdBits.clear();
2799
2800 mPointerVelocityControl.reset();
2801 return true;
2802 }
2803 }
2804
2805 // We did not handle this timeout.
2806 return false;
2807 }
2808
2809 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2810 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2811
2812 // Update the velocity tracker.
2813 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002814 std::vector<float> positionsX;
2815 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002816 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002817 uint32_t id = idBits.clearFirstMarkedBit();
2818 const RawPointerData::Pointer& pointer =
2819 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002820 positionsX.push_back(pointer.x * mPointerXMovementScale);
2821 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822 }
2823 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002824 {{AMOTION_EVENT_AXIS_X, positionsX},
2825 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826 }
2827
2828 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2829 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002830 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2831 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2832 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002833 mPointerGesture.resetTap();
2834 }
2835
2836 // Pick a new active touch id if needed.
2837 // Choose an arbitrary pointer that just went down, if there is one.
2838 // Otherwise choose an arbitrary remaining pointer.
2839 // This guarantees we always have an active touch id when there is at least one pointer.
2840 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002841 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002842 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002843 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002844 mPointerGesture.firstTouchTime = when;
2845 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002846 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2847 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2848 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2849 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002850 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002851 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002852
2853 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002854 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002856 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2857 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2858 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002859 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002860 *outFinishPreviousGesture = true;
2861 }
2862
2863 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002864 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 mPointerGesture.currentGestureIdBits.clear();
2866
2867 mPointerVelocityControl.reset();
2868 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2869 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2870 // The pointer follows the active touch point.
2871 // Emit DOWN, MOVE, UP events at the pointer location.
2872 //
2873 // Only the active touch matters; other fingers are ignored. This policy helps
2874 // to handle the case where the user places a second finger on the touch pad
2875 // to apply the necessary force to depress an integrated button below the surface.
2876 // We don't want the second finger to be delivered to applications.
2877 //
2878 // For this to work well, we need to make sure to track the pointer that is really
2879 // active. If the user first puts one finger down to click then adds another
2880 // finger to drag then the active pointer should switch to the finger that is
2881 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002882 ALOGD_IF(DEBUG_GESTURES,
2883 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2884 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002886 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002887 *outFinishPreviousGesture = true;
2888 mPointerGesture.activeGestureId = 0;
2889 }
2890
2891 // Switch pointers if needed.
2892 // Find the fastest pointer and follow it.
2893 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002894 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002896 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002897 ALOGD_IF(DEBUG_GESTURES,
2898 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2899 "bestSpeed=%0.3f",
2900 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002901 }
2902 }
2903
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002904 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002905 // When using spots, the click will occur at the position of the anchor
2906 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002907 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002908 } else {
2909 mPointerVelocityControl.reset();
2910 }
2911
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002912 float x, y;
2913 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002914
Michael Wright227c5542020-07-02 18:30:52 +01002915 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916 mPointerGesture.currentGestureIdBits.clear();
2917 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2918 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2919 mPointerGesture.currentGestureProperties[0].clear();
2920 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2921 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2922 mPointerGesture.currentGestureCoords[0].clear();
2923 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2924 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2925 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2926 } else if (currentFingerCount == 0) {
2927 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002928 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002929 *outFinishPreviousGesture = true;
2930 }
2931
2932 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2933 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2934 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002935 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2936 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002937 lastFingerCount == 1) {
2938 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002939 float x, y;
2940 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002941 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2942 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002943 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944
2945 mPointerGesture.tapUpTime = when;
2946 getContext()->requestTimeoutAtTime(when +
2947 mConfig.pointerGestureTapDragInterval);
2948
2949 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002950 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 mPointerGesture.currentGestureIdBits.clear();
2952 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2953 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2954 mPointerGesture.currentGestureProperties[0].clear();
2955 mPointerGesture.currentGestureProperties[0].id =
2956 mPointerGesture.activeGestureId;
2957 mPointerGesture.currentGestureProperties[0].toolType =
2958 AMOTION_EVENT_TOOL_TYPE_FINGER;
2959 mPointerGesture.currentGestureCoords[0].clear();
2960 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2961 mPointerGesture.tapX);
2962 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2963 mPointerGesture.tapY);
2964 mPointerGesture.currentGestureCoords[0]
2965 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2966
2967 tapped = true;
2968 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002969 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2970 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002971 }
2972 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002973 if (DEBUG_GESTURES) {
2974 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2975 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2976 (when - mPointerGesture.tapDownTime) * 0.000001f);
2977 } else {
2978 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2979 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002980 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 }
2982 }
2983
2984 mPointerVelocityControl.reset();
2985
2986 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002987 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002989 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 mPointerGesture.currentGestureIdBits.clear();
2991 }
2992 } else if (currentFingerCount == 1) {
2993 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2994 // The pointer follows the active touch point.
2995 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2996 // When in TAP_DRAG, emit MOVE events at the pointer location.
2997 ALOG_ASSERT(activeTouchId >= 0);
2998
Michael Wright227c5542020-07-02 18:30:52 +01002999 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3000 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003001 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003002 float x, y;
3003 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003004 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3005 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003006 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003007 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003008 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3009 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003010 }
3011 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003012 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3013 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003014 }
Michael Wright227c5542020-07-02 18:30:52 +01003015 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3016 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003017 }
3018
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003019 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003020 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003021 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003022 } else {
3023 mPointerVelocityControl.reset();
3024 }
3025
3026 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003027 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003028 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003029 down = true;
3030 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003031 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003032 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003033 *outFinishPreviousGesture = true;
3034 }
3035 mPointerGesture.activeGestureId = 0;
3036 down = false;
3037 }
3038
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003039 float x, y;
3040 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003041
3042 mPointerGesture.currentGestureIdBits.clear();
3043 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3044 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3045 mPointerGesture.currentGestureProperties[0].clear();
3046 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3047 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3048 mPointerGesture.currentGestureCoords[0].clear();
3049 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3050 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3051 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3052 down ? 1.0f : 0.0f);
3053
3054 if (lastFingerCount == 0 && currentFingerCount != 0) {
3055 mPointerGesture.resetTap();
3056 mPointerGesture.tapDownTime = when;
3057 mPointerGesture.tapX = x;
3058 mPointerGesture.tapY = y;
3059 }
3060 } else {
3061 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003062 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003063 }
3064
3065 mPointerController->setButtonState(mCurrentRawState.buttonState);
3066
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003067 if (DEBUG_GESTURES) {
3068 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3069 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3070 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3071 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3072 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3073 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3074 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3075 uint32_t id = idBits.clearFirstMarkedBit();
3076 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3077 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3078 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3079 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3080 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3081 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3082 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3083 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3084 }
3085 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3086 uint32_t id = idBits.clearFirstMarkedBit();
3087 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3088 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3089 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3090 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3091 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3092 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3093 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3094 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3095 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003096 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003097 return true;
3098}
3099
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003100bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3101 if (mPointerGesture.activeTouchId < 0) {
3102 mPointerGesture.resetQuietTime();
3103 return false;
3104 }
3105
3106 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3107 return true;
3108 }
3109
3110 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3111 bool isQuietTime = false;
3112 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3113 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3114 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3115 currentFingerCount < 2) {
3116 // Enter quiet time when exiting swipe or freeform state.
3117 // This is to prevent accidentally entering the hover state and flinging the
3118 // pointer when finishing a swipe and there is still one pointer left onscreen.
3119 isQuietTime = true;
3120 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3121 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3122 // Enter quiet time when releasing the button and there are still two or more
3123 // fingers down. This may indicate that one finger was used to press the button
3124 // but it has not gone up yet.
3125 isQuietTime = true;
3126 }
3127 if (isQuietTime) {
3128 mPointerGesture.quietTime = when;
3129 }
3130 return isQuietTime;
3131}
3132
3133std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3134 int32_t bestId = -1;
3135 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3136 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3137 uint32_t id = idBits.clearFirstMarkedBit();
3138 std::optional<float> vx =
3139 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3140 std::optional<float> vy =
3141 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3142 if (vx && vy) {
3143 float speed = hypotf(*vx, *vy);
3144 if (speed > bestSpeed) {
3145 bestId = id;
3146 bestSpeed = speed;
3147 }
3148 }
3149 }
3150 return std::make_pair(bestId, bestSpeed);
3151}
3152
3153void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3154 bool* finishPreviousGesture) {
3155 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3156 // to move before deciding what to do.
3157 //
3158 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3159 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3160 // just a press or long-press at the pointer location.
3161 //
3162 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3163 // pointer location.
3164 //
3165 // When the two fingers move enough or when additional fingers are added, we make a decision to
3166 // transition into SWIPE or FREEFORM mode accordingly.
3167 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3168 ALOG_ASSERT(activeTouchId >= 0);
3169
3170 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3171 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3172 bool settled =
3173 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3174 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3175 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3176 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3177 *finishPreviousGesture = true;
3178 } else if (!settled && currentFingerCount > lastFingerCount) {
3179 // Additional pointers have gone down but not yet settled.
3180 // Reset the gesture.
3181 ALOGD_IF(DEBUG_GESTURES,
3182 "Gestures: Resetting gesture since additional pointers went down for "
3183 "MULTITOUCH, settle time remaining %0.3fms",
3184 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3185 when) * 0.000001f);
3186 *cancelPreviousGesture = true;
3187 } else {
3188 // Continue previous gesture.
3189 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3190 }
3191
3192 if (*finishPreviousGesture || *cancelPreviousGesture) {
3193 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3194 mPointerGesture.activeGestureId = 0;
3195 mPointerGesture.referenceIdBits.clear();
3196 mPointerVelocityControl.reset();
3197
3198 // Use the centroid and pointer location as the reference points for the gesture.
3199 ALOGD_IF(DEBUG_GESTURES,
3200 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3201 "%0.3fms",
3202 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3203 when) * 0.000001f);
3204 mCurrentRawState.rawPointerData
3205 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3206 &mPointerGesture.referenceTouchY);
3207 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3208 &mPointerGesture.referenceGestureY);
3209 }
3210
3211 // Clear the reference deltas for fingers not yet included in the reference calculation.
3212 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3213 ~mPointerGesture.referenceIdBits.value);
3214 !idBits.isEmpty();) {
3215 uint32_t id = idBits.clearFirstMarkedBit();
3216 mPointerGesture.referenceDeltas[id].dx = 0;
3217 mPointerGesture.referenceDeltas[id].dy = 0;
3218 }
3219 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3220
3221 // Add delta for all fingers and calculate a common movement delta.
3222 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3223 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3224 mCurrentCookedState.fingerIdBits.value);
3225 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3226 bool first = (idBits == commonIdBits);
3227 uint32_t id = idBits.clearFirstMarkedBit();
3228 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3229 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3230 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3231 delta.dx += cpd.x - lpd.x;
3232 delta.dy += cpd.y - lpd.y;
3233
3234 if (first) {
3235 commonDeltaRawX = delta.dx;
3236 commonDeltaRawY = delta.dy;
3237 } else {
3238 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3239 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3240 }
3241 }
3242
3243 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3244 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3245 float dist[MAX_POINTER_ID + 1];
3246 int32_t distOverThreshold = 0;
3247 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3248 uint32_t id = idBits.clearFirstMarkedBit();
3249 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3250 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3251 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3252 distOverThreshold += 1;
3253 }
3254 }
3255
3256 // Only transition when at least two pointers have moved further than
3257 // the minimum distance threshold.
3258 if (distOverThreshold >= 2) {
3259 if (currentFingerCount > 2) {
3260 // There are more than two pointers, switch to FREEFORM.
3261 ALOGD_IF(DEBUG_GESTURES,
3262 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3263 currentFingerCount);
3264 *cancelPreviousGesture = true;
3265 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3266 } else {
3267 // There are exactly two pointers.
3268 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3269 uint32_t id1 = idBits.clearFirstMarkedBit();
3270 uint32_t id2 = idBits.firstMarkedBit();
3271 const RawPointerData::Pointer& p1 =
3272 mCurrentRawState.rawPointerData.pointerForId(id1);
3273 const RawPointerData::Pointer& p2 =
3274 mCurrentRawState.rawPointerData.pointerForId(id2);
3275 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3276 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3277 // There are two pointers but they are too far apart for a SWIPE,
3278 // switch to FREEFORM.
3279 ALOGD_IF(DEBUG_GESTURES,
3280 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3281 mutualDistance, mPointerGestureMaxSwipeWidth);
3282 *cancelPreviousGesture = true;
3283 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3284 } else {
3285 // There are two pointers. Wait for both pointers to start moving
3286 // before deciding whether this is a SWIPE or FREEFORM gesture.
3287 float dist1 = dist[id1];
3288 float dist2 = dist[id2];
3289 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3290 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3291 // Calculate the dot product of the displacement vectors.
3292 // When the vectors are oriented in approximately the same direction,
3293 // the angle betweeen them is near zero and the cosine of the angle
3294 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3295 // mag(v2).
3296 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3297 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3298 float dx1 = delta1.dx * mPointerXZoomScale;
3299 float dy1 = delta1.dy * mPointerYZoomScale;
3300 float dx2 = delta2.dx * mPointerXZoomScale;
3301 float dy2 = delta2.dy * mPointerYZoomScale;
3302 float dot = dx1 * dx2 + dy1 * dy2;
3303 float cosine = dot / (dist1 * dist2); // denominator always > 0
3304 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3305 // Pointers are moving in the same direction. Switch to SWIPE.
3306 ALOGD_IF(DEBUG_GESTURES,
3307 "Gestures: PRESS transitioned to SWIPE, "
3308 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3309 "cosine %0.3f >= %0.3f",
3310 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3311 mConfig.pointerGestureMultitouchMinDistance, cosine,
3312 mConfig.pointerGestureSwipeTransitionAngleCosine);
3313 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3314 } else {
3315 // Pointers are moving in different directions. Switch to FREEFORM.
3316 ALOGD_IF(DEBUG_GESTURES,
3317 "Gestures: PRESS transitioned to FREEFORM, "
3318 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3319 "cosine %0.3f < %0.3f",
3320 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3321 mConfig.pointerGestureMultitouchMinDistance, cosine,
3322 mConfig.pointerGestureSwipeTransitionAngleCosine);
3323 *cancelPreviousGesture = true;
3324 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3325 }
3326 }
3327 }
3328 }
3329 }
3330 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3331 // Switch from SWIPE to FREEFORM if additional pointers go down.
3332 // Cancel previous gesture.
3333 if (currentFingerCount > 2) {
3334 ALOGD_IF(DEBUG_GESTURES,
3335 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3336 currentFingerCount);
3337 *cancelPreviousGesture = true;
3338 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3339 }
3340 }
3341
3342 // Move the reference points based on the overall group motion of the fingers
3343 // except in PRESS mode while waiting for a transition to occur.
3344 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3345 (commonDeltaRawX || commonDeltaRawY)) {
3346 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3347 uint32_t id = idBits.clearFirstMarkedBit();
3348 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3349 delta.dx = 0;
3350 delta.dy = 0;
3351 }
3352
3353 mPointerGesture.referenceTouchX += commonDeltaRawX;
3354 mPointerGesture.referenceTouchY += commonDeltaRawY;
3355
3356 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3357 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3358
3359 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3360 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3361
3362 mPointerGesture.referenceGestureX += commonDeltaX;
3363 mPointerGesture.referenceGestureY += commonDeltaY;
3364 }
3365
3366 // Report gestures.
3367 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3368 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3369 // PRESS or SWIPE mode.
3370 ALOGD_IF(DEBUG_GESTURES,
3371 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3372 "currentTouchPointerCount=%d",
3373 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3374 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3375
3376 mPointerGesture.currentGestureIdBits.clear();
3377 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3378 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3379 mPointerGesture.currentGestureProperties[0].clear();
3380 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3381 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3382 mPointerGesture.currentGestureCoords[0].clear();
3383 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3384 mPointerGesture.referenceGestureX);
3385 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3386 mPointerGesture.referenceGestureY);
3387 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3388 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3389 float xOffset = static_cast<float>(commonDeltaRawX) /
3390 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3391 float yOffset = static_cast<float>(commonDeltaRawY) /
3392 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3393 mPointerGesture.currentGestureCoords[0]
3394 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3395 mPointerGesture.currentGestureCoords[0]
3396 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3397 }
3398 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3399 // FREEFORM mode.
3400 ALOGD_IF(DEBUG_GESTURES,
3401 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3402 "currentTouchPointerCount=%d",
3403 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3404 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3405
3406 mPointerGesture.currentGestureIdBits.clear();
3407
3408 BitSet32 mappedTouchIdBits;
3409 BitSet32 usedGestureIdBits;
3410 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3411 // Initially, assign the active gesture id to the active touch point
3412 // if there is one. No other touch id bits are mapped yet.
3413 if (!*cancelPreviousGesture) {
3414 mappedTouchIdBits.markBit(activeTouchId);
3415 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3416 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3417 mPointerGesture.activeGestureId;
3418 } else {
3419 mPointerGesture.activeGestureId = -1;
3420 }
3421 } else {
3422 // Otherwise, assume we mapped all touches from the previous frame.
3423 // Reuse all mappings that are still applicable.
3424 mappedTouchIdBits.value =
3425 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3426 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3427
3428 // Check whether we need to choose a new active gesture id because the
3429 // current went went up.
3430 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3431 ~mCurrentCookedState.fingerIdBits.value);
3432 !upTouchIdBits.isEmpty();) {
3433 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3434 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3435 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3436 mPointerGesture.activeGestureId = -1;
3437 break;
3438 }
3439 }
3440 }
3441
3442 ALOGD_IF(DEBUG_GESTURES,
3443 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3444 "activeGestureId=%d",
3445 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3446
3447 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3448 for (uint32_t i = 0; i < currentFingerCount; i++) {
3449 uint32_t touchId = idBits.clearFirstMarkedBit();
3450 uint32_t gestureId;
3451 if (!mappedTouchIdBits.hasBit(touchId)) {
3452 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3453 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3454 ALOGD_IF(DEBUG_GESTURES,
3455 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3456 gestureId);
3457 } else {
3458 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3459 ALOGD_IF(DEBUG_GESTURES,
3460 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3461 touchId, gestureId);
3462 }
3463 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3464 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3465
3466 const RawPointerData::Pointer& pointer =
3467 mCurrentRawState.rawPointerData.pointerForId(touchId);
3468 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3469 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3470 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3471
3472 mPointerGesture.currentGestureProperties[i].clear();
3473 mPointerGesture.currentGestureProperties[i].id = gestureId;
3474 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3475 mPointerGesture.currentGestureCoords[i].clear();
3476 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3477 mPointerGesture.referenceGestureX +
3478 deltaX);
3479 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3480 mPointerGesture.referenceGestureY +
3481 deltaY);
3482 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3483 }
3484
3485 if (mPointerGesture.activeGestureId < 0) {
3486 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3487 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3488 mPointerGesture.activeGestureId);
3489 }
3490 }
3491}
3492
Harry Cutts714d1ad2022-08-24 16:36:43 +00003493void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3494 const RawPointerData::Pointer& currentPointer =
3495 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3496 const RawPointerData::Pointer& lastPointer =
3497 mLastRawState.rawPointerData.pointerForId(pointerId);
3498 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3499 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3500
3501 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3502 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3503
3504 mPointerController->move(deltaX, deltaY);
3505}
3506
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003507std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3508 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509 mPointerSimple.currentCoords.clear();
3510 mPointerSimple.currentProperties.clear();
3511
3512 bool down, hovering;
3513 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3514 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3515 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003516 mPointerController
3517 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3518 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003519
3520 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3521 down = !hovering;
3522
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003523 float x, y;
3524 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003525 mPointerSimple.currentCoords.copyFrom(
3526 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3527 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3528 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3529 mPointerSimple.currentProperties.id = 0;
3530 mPointerSimple.currentProperties.toolType =
3531 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3532 } else {
3533 down = false;
3534 hovering = false;
3535 }
3536
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003537 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003538}
3539
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003540std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3541 uint32_t policyFlags) {
3542 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003543}
3544
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003545std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3546 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003547 mPointerSimple.currentCoords.clear();
3548 mPointerSimple.currentProperties.clear();
3549
3550 bool down, hovering;
3551 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3552 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003553 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003554 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003555 } else {
3556 mPointerVelocityControl.reset();
3557 }
3558
3559 down = isPointerDown(mCurrentRawState.buttonState);
3560 hovering = !down;
3561
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003562 float x, y;
3563 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003564 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003565 mPointerSimple.currentCoords.copyFrom(
3566 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3567 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3568 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3569 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3570 hovering ? 0.0f : 1.0f);
3571 mPointerSimple.currentProperties.id = 0;
3572 mPointerSimple.currentProperties.toolType =
3573 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3574 } else {
3575 mPointerVelocityControl.reset();
3576
3577 down = false;
3578 hovering = false;
3579 }
3580
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003581 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003582}
3583
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003584std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3585 uint32_t policyFlags) {
3586 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003587
3588 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003589
3590 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003591}
3592
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003593std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3594 uint32_t policyFlags, bool down,
3595 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003596 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3597 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003598 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003599 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003600
3601 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003602 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003603 mPointerController->clearSpots();
3604 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003605 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003607 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003608 }
Garfield Tan9514d782020-11-10 16:37:23 -08003609 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003610
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003611 float xCursorPosition, yCursorPosition;
3612 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003613
3614 if (mPointerSimple.down && !down) {
3615 mPointerSimple.down = false;
3616
3617 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003618 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3619 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3620 0, metaState, mLastRawState.buttonState,
3621 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3622 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3623 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3624 yCursorPosition, mPointerSimple.downTime,
3625 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003626 }
3627
3628 if (mPointerSimple.hovering && !hovering) {
3629 mPointerSimple.hovering = false;
3630
3631 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003632 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3633 mSource, displayId, policyFlags,
3634 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3635 mLastRawState.buttonState, MotionClassification::NONE,
3636 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3637 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3638 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3639 yCursorPosition, mPointerSimple.downTime,
3640 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003641 }
3642
3643 if (down) {
3644 if (!mPointerSimple.down) {
3645 mPointerSimple.down = true;
3646 mPointerSimple.downTime = when;
3647
3648 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003649 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3650 mSource, displayId, policyFlags,
3651 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3652 mCurrentRawState.buttonState, MotionClassification::NONE,
3653 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3654 &mPointerSimple.currentProperties,
3655 &mPointerSimple.currentCoords, mOrientedXPrecision,
3656 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3657 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003658 }
3659
3660 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003661 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3662 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3663 0, 0, metaState, mCurrentRawState.buttonState,
3664 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3665 &mPointerSimple.currentProperties,
3666 &mPointerSimple.currentCoords, mOrientedXPrecision,
3667 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3668 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003669 }
3670
3671 if (hovering) {
3672 if (!mPointerSimple.hovering) {
3673 mPointerSimple.hovering = true;
3674
3675 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003676 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3677 mSource, displayId, policyFlags,
3678 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3679 mCurrentRawState.buttonState, MotionClassification::NONE,
3680 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3681 &mPointerSimple.currentProperties,
3682 &mPointerSimple.currentCoords, mOrientedXPrecision,
3683 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3684 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003685 }
3686
3687 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003688 out.push_back(
3689 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3690 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3691 metaState, mCurrentRawState.buttonState,
3692 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3693 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3694 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3695 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696 }
3697
3698 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3699 float vscroll = mCurrentRawState.rawVScroll;
3700 float hscroll = mCurrentRawState.rawHScroll;
3701 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3702 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3703
3704 // Send scroll.
3705 PointerCoords pointerCoords;
3706 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3707 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3708 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3709
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003710 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3711 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3712 0, 0, metaState, mCurrentRawState.buttonState,
3713 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3714 &mPointerSimple.currentProperties, &pointerCoords,
3715 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3716 yCursorPosition, mPointerSimple.downTime,
3717 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003718 }
3719
3720 // Save state.
3721 if (down || hovering) {
3722 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3723 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003724 mPointerSimple.displayId = displayId;
3725 mPointerSimple.source = mSource;
3726 mPointerSimple.lastCursorX = xCursorPosition;
3727 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003728 } else {
3729 mPointerSimple.reset();
3730 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003731 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003732}
3733
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003734std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3735 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003736 std::list<NotifyArgs> out;
3737 if (mPointerSimple.down || mPointerSimple.hovering) {
3738 int32_t metaState = getContext()->getGlobalMetaState();
3739 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3740 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3741 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3742 metaState, mLastRawState.buttonState,
3743 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3744 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3745 mOrientedXPrecision, mOrientedYPrecision,
3746 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3747 mPointerSimple.downTime,
3748 /* videoFrames */ {}));
3749 if (mPointerController != nullptr) {
3750 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3751 }
3752 }
3753 mPointerSimple.reset();
3754 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003755}
3756
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003757NotifyMotionArgs TouchInputMapper::dispatchMotion(
3758 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3759 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003760 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3761 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003762 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003763 PointerCoords pointerCoords[MAX_POINTERS];
3764 PointerProperties pointerProperties[MAX_POINTERS];
3765 uint32_t pointerCount = 0;
3766 while (!idBits.isEmpty()) {
3767 uint32_t id = idBits.clearFirstMarkedBit();
3768 uint32_t index = idToIndex[id];
3769 pointerProperties[pointerCount].copyFrom(properties[index]);
3770 pointerCoords[pointerCount].copyFrom(coords[index]);
3771
3772 if (changedId >= 0 && id == uint32_t(changedId)) {
3773 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3774 }
3775
3776 pointerCount += 1;
3777 }
3778
3779 ALOG_ASSERT(pointerCount != 0);
3780
3781 if (changedId >= 0 && pointerCount == 1) {
3782 // Replace initial down and final up action.
3783 // We can compare the action without masking off the changed pointer index
3784 // because we know the index is 0.
3785 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3786 action = AMOTION_EVENT_ACTION_DOWN;
3787 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003788 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3789 action = AMOTION_EVENT_ACTION_CANCEL;
3790 } else {
3791 action = AMOTION_EVENT_ACTION_UP;
3792 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003793 } else {
3794 // Can't happen.
3795 ALOG_ASSERT(false);
3796 }
3797 }
3798 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3799 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003800 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003801 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003802 }
3803 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3804 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003805 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003806 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003807 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003808 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3809 policyFlags, action, actionButton, flags, metaState, buttonState,
3810 classification, edgeFlags, pointerCount, pointerProperties,
3811 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3812 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003813}
3814
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003815std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3816 std::list<NotifyArgs> out;
3817 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3818 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3819 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003820}
3821
Prabir Pradhan1728b212021-10-19 16:00:03 -07003822// Transform input device coordinates to display panel coordinates.
3823void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003824 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3825 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3826
arthurhunga36b28e2020-12-29 20:28:15 +08003827 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3828 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3829
Prabir Pradhan1728b212021-10-19 16:00:03 -07003830 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003831 // 0 - no swap and reverse.
3832 // 90 - swap x/y and reverse y.
3833 // 180 - reverse x, y.
3834 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003835 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003836 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003837 x = xScaled;
3838 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003839 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003840 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003841 y = xScaledMax;
3842 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003843 break;
3844 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003845 x = xScaledMax;
3846 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003847 break;
3848 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003849 y = xScaled;
3850 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003851 break;
3852 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003853 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003854 }
3855}
3856
Prabir Pradhan1728b212021-10-19 16:00:03 -07003857bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003858 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3859 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3860
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003861 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003862 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003863 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003864 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003865}
3866
3867const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3868 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003869 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3870 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3871 "left=%d, top=%d, right=%d, bottom=%d",
3872 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3873 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003874
3875 if (virtualKey.isHit(x, y)) {
3876 return &virtualKey;
3877 }
3878 }
3879
3880 return nullptr;
3881}
3882
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003883void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3884 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3885 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003886
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003887 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003888
3889 if (currentPointerCount == 0) {
3890 // No pointers to assign.
3891 return;
3892 }
3893
3894 if (lastPointerCount == 0) {
3895 // All pointers are new.
3896 for (uint32_t i = 0; i < currentPointerCount; i++) {
3897 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003898 current.rawPointerData.pointers[i].id = id;
3899 current.rawPointerData.idToIndex[id] = i;
3900 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003901 }
3902 return;
3903 }
3904
3905 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003906 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003907 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003908 uint32_t id = last.rawPointerData.pointers[0].id;
3909 current.rawPointerData.pointers[0].id = id;
3910 current.rawPointerData.idToIndex[id] = 0;
3911 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003912 return;
3913 }
3914
3915 // General case.
3916 // We build a heap of squared euclidean distances between current and last pointers
3917 // associated with the current and last pointer indices. Then, we find the best
3918 // match (by distance) for each current pointer.
3919 // The pointers must have the same tool type but it is possible for them to
3920 // transition from hovering to touching or vice-versa while retaining the same id.
3921 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3922
3923 uint32_t heapSize = 0;
3924 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3925 currentPointerIndex++) {
3926 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3927 lastPointerIndex++) {
3928 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003929 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003930 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003931 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003932 if (currentPointer.toolType == lastPointer.toolType) {
3933 int64_t deltaX = currentPointer.x - lastPointer.x;
3934 int64_t deltaY = currentPointer.y - lastPointer.y;
3935
3936 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3937
3938 // Insert new element into the heap (sift up).
3939 heap[heapSize].currentPointerIndex = currentPointerIndex;
3940 heap[heapSize].lastPointerIndex = lastPointerIndex;
3941 heap[heapSize].distance = distance;
3942 heapSize += 1;
3943 }
3944 }
3945 }
3946
3947 // Heapify
3948 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3949 startIndex -= 1;
3950 for (uint32_t parentIndex = startIndex;;) {
3951 uint32_t childIndex = parentIndex * 2 + 1;
3952 if (childIndex >= heapSize) {
3953 break;
3954 }
3955
3956 if (childIndex + 1 < heapSize &&
3957 heap[childIndex + 1].distance < heap[childIndex].distance) {
3958 childIndex += 1;
3959 }
3960
3961 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3962 break;
3963 }
3964
3965 swap(heap[parentIndex], heap[childIndex]);
3966 parentIndex = childIndex;
3967 }
3968 }
3969
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003970 if (DEBUG_POINTER_ASSIGNMENT) {
3971 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3972 for (size_t i = 0; i < heapSize; i++) {
3973 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3974 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3975 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003976 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003977
3978 // Pull matches out by increasing order of distance.
3979 // To avoid reassigning pointers that have already been matched, the loop keeps track
3980 // of which last and current pointers have been matched using the matchedXXXBits variables.
3981 // It also tracks the used pointer id bits.
3982 BitSet32 matchedLastBits(0);
3983 BitSet32 matchedCurrentBits(0);
3984 BitSet32 usedIdBits(0);
3985 bool first = true;
3986 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3987 while (heapSize > 0) {
3988 if (first) {
3989 // The first time through the loop, we just consume the root element of
3990 // the heap (the one with smallest distance).
3991 first = false;
3992 } else {
3993 // Previous iterations consumed the root element of the heap.
3994 // Pop root element off of the heap (sift down).
3995 heap[0] = heap[heapSize];
3996 for (uint32_t parentIndex = 0;;) {
3997 uint32_t childIndex = parentIndex * 2 + 1;
3998 if (childIndex >= heapSize) {
3999 break;
4000 }
4001
4002 if (childIndex + 1 < heapSize &&
4003 heap[childIndex + 1].distance < heap[childIndex].distance) {
4004 childIndex += 1;
4005 }
4006
4007 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4008 break;
4009 }
4010
4011 swap(heap[parentIndex], heap[childIndex]);
4012 parentIndex = childIndex;
4013 }
4014
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004015 if (DEBUG_POINTER_ASSIGNMENT) {
4016 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4017 for (size_t j = 0; j < heapSize; j++) {
4018 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4019 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4020 heap[j].distance);
4021 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004022 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004023 }
4024
4025 heapSize -= 1;
4026
4027 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4028 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4029
4030 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4031 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4032
4033 matchedCurrentBits.markBit(currentPointerIndex);
4034 matchedLastBits.markBit(lastPointerIndex);
4035
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004036 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4037 current.rawPointerData.pointers[currentPointerIndex].id = id;
4038 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4039 current.rawPointerData.markIdBit(id,
4040 current.rawPointerData.isHovering(
4041 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004042 usedIdBits.markBit(id);
4043
Harry Cutts45483602022-08-24 14:36:48 +00004044 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4045 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4046 ", distance=%" PRIu64,
4047 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004048 break;
4049 }
4050 }
4051
4052 // Assign fresh ids to pointers that were not matched in the process.
4053 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4054 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4055 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4056
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004057 current.rawPointerData.pointers[currentPointerIndex].id = id;
4058 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4059 current.rawPointerData.markIdBit(id,
4060 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004061
Harry Cutts45483602022-08-24 14:36:48 +00004062 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4063 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4064 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004065 }
4066}
4067
4068int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4069 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4070 return AKEY_STATE_VIRTUAL;
4071 }
4072
4073 for (const VirtualKey& virtualKey : mVirtualKeys) {
4074 if (virtualKey.keyCode == keyCode) {
4075 return AKEY_STATE_UP;
4076 }
4077 }
4078
4079 return AKEY_STATE_UNKNOWN;
4080}
4081
4082int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4083 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4084 return AKEY_STATE_VIRTUAL;
4085 }
4086
4087 for (const VirtualKey& virtualKey : mVirtualKeys) {
4088 if (virtualKey.scanCode == scanCode) {
4089 return AKEY_STATE_UP;
4090 }
4091 }
4092
4093 return AKEY_STATE_UNKNOWN;
4094}
4095
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004096bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4097 const std::vector<int32_t>& keyCodes,
4098 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004099 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004100 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004101 if (virtualKey.keyCode == keyCodes[i]) {
4102 outFlags[i] = 1;
4103 }
4104 }
4105 }
4106
4107 return true;
4108}
4109
4110std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4111 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004112 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004113 return std::make_optional(mPointerController->getDisplayId());
4114 } else {
4115 return std::make_optional(mViewport.displayId);
4116 }
4117 }
4118 return std::nullopt;
4119}
4120
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004121} // namespace android