blob: 286e1f53b2d8a73b97a8aafd5b6b4f75004fb0e6 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
24
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070025#include "CursorButtonAccumulator.h"
26#include "CursorScrollAccumulator.h"
27#include "TouchButtonAccumulator.h"
28#include "TouchCursorInputMapperCommon.h"
29
30namespace android {
31
32// --- Constants ---
33
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070034// Artificial latency on synthetic events created from stylus data without corresponding touch
35// data.
36static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
37
HQ Liue6983c72022-04-19 22:14:56 +000038// Minimum width between two pointers to determine a gesture as freeform gesture in mm
39static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070040// --- Static Definitions ---
41
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000042static const DisplayViewport kUninitializedViewport;
43
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070044template <typename T>
45inline static void swap(T& a, T& b) {
46 T temp = a;
47 a = b;
48 b = temp;
49}
50
51static float calculateCommonVector(float a, float b) {
52 if (a > 0 && b > 0) {
53 return a < b ? a : b;
54 } else if (a < 0 && b < 0) {
55 return a > b ? a : b;
56 } else {
57 return 0;
58 }
59}
60
61inline static float distance(float x1, float y1, float x2, float y2) {
62 return hypotf(x1 - x2, y1 - y2);
63}
64
65inline static int32_t signExtendNybble(int32_t value) {
66 return value >= 8 ? value - 16 : value;
67}
68
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070069// --- RawPointerData ---
70
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070071void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
72 float x = 0, y = 0;
73 uint32_t count = touchingIdBits.count();
74 if (count) {
75 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
76 uint32_t id = idBits.clearFirstMarkedBit();
77 const Pointer& pointer = pointerForId(id);
78 x += pointer.x;
79 y += pointer.y;
80 }
81 x /= count;
82 y /= count;
83 }
84 *outX = x;
85 *outY = y;
86}
87
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070088// --- TouchInputMapper ---
89
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -080090TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
91 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +000092 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070093 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +010094 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -070095 mDisplayWidth(-1),
96 mDisplayHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070097 mPhysicalWidth(-1),
98 mPhysicalHeight(-1),
99 mPhysicalLeft(0),
100 mPhysicalTop(0),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700101 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700102
103TouchInputMapper::~TouchInputMapper() {}
104
Philip Junker4af3b3d2021-12-14 10:36:55 +0100105uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700106 return mSource;
107}
108
109void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
110 InputMapper::populateDeviceInfo(info);
111
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000112 if (mDeviceMode == DeviceMode::DISABLED) {
113 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700114 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000115
116 info->addMotionRange(mOrientedRanges.x);
117 info->addMotionRange(mOrientedRanges.y);
118 info->addMotionRange(mOrientedRanges.pressure);
119
120 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
121 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
122 //
123 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
124 // motion, i.e. the hardware dimensions, as the finger could move completely across the
125 // touchpad in one sample cycle.
126 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
127 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
128 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
129 x.resolution);
130 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
131 y.resolution);
132 }
133
134 if (mOrientedRanges.size) {
135 info->addMotionRange(*mOrientedRanges.size);
136 }
137
138 if (mOrientedRanges.touchMajor) {
139 info->addMotionRange(*mOrientedRanges.touchMajor);
140 info->addMotionRange(*mOrientedRanges.touchMinor);
141 }
142
143 if (mOrientedRanges.toolMajor) {
144 info->addMotionRange(*mOrientedRanges.toolMajor);
145 info->addMotionRange(*mOrientedRanges.toolMinor);
146 }
147
148 if (mOrientedRanges.orientation) {
149 info->addMotionRange(*mOrientedRanges.orientation);
150 }
151
152 if (mOrientedRanges.distance) {
153 info->addMotionRange(*mOrientedRanges.distance);
154 }
155
156 if (mOrientedRanges.tilt) {
157 info->addMotionRange(*mOrientedRanges.tilt);
158 }
159
160 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
161 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
162 }
163 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
164 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
165 }
166 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
167 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
168 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
169 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
170 x.resolution);
171 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
172 y.resolution);
173 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
174 x.resolution);
175 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
176 y.resolution);
177 }
178 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000179 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700180}
181
182void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700183 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800184 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700185 dumpParameters(dump);
186 dumpVirtualKeys(dump);
187 dumpRawPointerAxes(dump);
188 dumpCalibration(dump);
189 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700190 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700191
192 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700193 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
194 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
195 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
196 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
197 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
198 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
199 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
200 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
201 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
202 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
203 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
204 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
205 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
206 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
207
208 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
209 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
210 mLastRawState.rawPointerData.pointerCount);
211 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
212 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
213 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
214 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
215 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
216 "toolType=%d, isHovering=%s\n",
217 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
218 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
219 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
220 pointer.distance, pointer.toolType, toString(pointer.isHovering));
221 }
222
223 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
224 mLastCookedState.buttonState);
225 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
226 mLastCookedState.cookedPointerData.pointerCount);
227 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
228 const PointerProperties& pointerProperties =
229 mLastCookedState.cookedPointerData.pointerProperties[i];
230 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000231 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
232 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
233 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700234 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
235 "toolType=%d, isHovering=%s\n",
236 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000237 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
238 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700239 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
240 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
241 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
242 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
243 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
244 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
245 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
246 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
247 pointerProperties.toolType,
248 toString(mLastCookedState.cookedPointerData.isHovering(i)));
249 }
250
251 dump += INDENT3 "Stylus Fusion:\n";
252 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
253 toString(mExternalStylusConnected));
254 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
255 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
256 mExternalStylusFusionTimeout);
257 dump += INDENT3 "External Stylus State:\n";
258 dumpStylusState(dump, mExternalStylusState);
259
Michael Wright227c5542020-07-02 18:30:52 +0100260 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700261 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
262 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
263 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
264 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
265 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
266 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
267 }
268}
269
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700270std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
271 const InputReaderConfiguration* config,
272 uint32_t changes) {
273 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700274
275 mConfig = *config;
276
277 if (!changes) { // first time only
278 // Configure basic parameters.
279 configureParameters();
280
281 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800282 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000283 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700284
285 // Configure absolute axis information.
286 configureRawPointerAxes();
287
288 // Prepare input device calibration.
289 parseCalibration();
290 resolveCalibration();
291 }
292
293 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
294 // Update location calibration to reflect current settings
295 updateAffineTransformation();
296 }
297
298 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
299 // Update pointer speed.
300 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
301 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
302 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
303 }
304
305 bool resetNeeded = false;
306 if (!changes ||
307 (changes &
308 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800309 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700310 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
311 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
312 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700313 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700315 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700316 }
317
318 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700319 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000320
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700321 // Send reset, unless this is the first time the device has been configured,
322 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000323 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700324 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700325 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700326}
327
328void TouchInputMapper::resolveExternalStylusPresence() {
329 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800330 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700331 mExternalStylusConnected = !devices.empty();
332
333 if (!mExternalStylusConnected) {
334 resetExternalStylus();
335 }
336}
337
338void TouchInputMapper::configureParameters() {
339 // Use the pointer presentation mode for devices that do not support distinct
340 // multitouch. The spot-based presentation relies on being able to accurately
341 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800342 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100343 ? Parameters::GestureMode::SINGLE_TOUCH
344 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700346 std::string gestureModeString;
347 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800348 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700349 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100350 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100352 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700353 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700354 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355 }
356 }
357
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800358 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700359 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100360 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700362 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100363 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364 } else {
365 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100366 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700367 }
368
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800369 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700370
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700371 std::string deviceTypeString;
372 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800373 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100375 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700376 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100377 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700378 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100379 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700380 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700381 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700382 }
383 }
384
Michael Wright227c5542020-07-02 18:30:52 +0100385 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700386 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800387 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700388
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700389 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700390 std::string orientationString;
391 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700392 orientationString)) {
393 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
394 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
395 } else if (orientationString == "ORIENTATION_90") {
396 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
397 } else if (orientationString == "ORIENTATION_180") {
398 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
399 } else if (orientationString == "ORIENTATION_270") {
400 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
401 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700402 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700403 }
404 }
405
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700406 mParameters.hasAssociatedDisplay = false;
407 mParameters.associatedDisplayIsExternal = false;
408 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100409 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
410 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700411 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100412 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800413 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700414 std::string uniqueDisplayId;
415 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800416 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700417 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
418 }
419 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800420 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421 mParameters.hasAssociatedDisplay = true;
422 }
423
424 // Initial downs on external touch devices should wake the device.
425 // Normally we don't do this for internal touch screens to prevent them from waking
426 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800427 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700428 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000429
430 mParameters.supportsUsi = false;
431 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
432 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700433
434 mParameters.enableForInactiveViewport = false;
435 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
436 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700437}
438
439void TouchInputMapper::dumpParameters(std::string& dump) {
440 dump += INDENT3 "Parameters:\n";
441
Dominik Laskowski75788452021-02-09 18:51:25 -0800442 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443
Dominik Laskowski75788452021-02-09 18:51:25 -0800444 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700445
446 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
447 "displayId='%s'\n",
448 toString(mParameters.hasAssociatedDisplay),
449 toString(mParameters.associatedDisplayIsExternal),
450 mParameters.uniqueDisplayId.c_str());
451 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800452 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000453 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700454 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
455 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456}
457
458void TouchInputMapper::configureRawPointerAxes() {
459 mRawPointerAxes.clear();
460}
461
462void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
463 dump += INDENT3 "Raw Touch Axes:\n";
464 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
465 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
466 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
467 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
468 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
469 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
470 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
471 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
472 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
473 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
474 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
475 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
476 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
477}
478
479bool TouchInputMapper::hasExternalStylus() const {
480 return mExternalStylusConnected;
481}
482
483/**
484 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000485 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800486 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000487 * 3. Get the matching viewport by either unique id in idc file or by the display type
488 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800489 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700490 */
491std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800492 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000493 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700495 }
496
Christine Franks2a2293c2022-01-18 11:51:16 -0800497 const std::optional<std::string> associatedDisplayUniqueId =
498 getDeviceContext().getAssociatedDisplayUniqueId();
499 if (associatedDisplayUniqueId) {
500 return getDeviceContext().getAssociatedViewport();
501 }
502
Michael Wright227c5542020-07-02 18:30:52 +0100503 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800504 std::optional<DisplayViewport> viewport =
505 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
506 if (viewport) {
507 return viewport;
508 } else {
509 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
510 mConfig.defaultPointerDisplayId);
511 }
512 }
513
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514 // Check if uniqueDisplayId is specified in idc file.
515 if (!mParameters.uniqueDisplayId.empty()) {
516 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
517 }
518
519 ViewportType viewportTypeToUse;
520 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100521 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700522 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100523 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700524 }
525
526 std::optional<DisplayViewport> viewport =
527 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100528 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700529 ALOGW("Input device %s should be associated with external display, "
530 "fallback to internal one for the external viewport is not found.",
531 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100532 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700533 }
534
535 return viewport;
536 }
537
538 // No associated display, return a non-display viewport.
539 DisplayViewport newViewport;
540 // Raw width and height in the natural orientation.
541 int32_t rawWidth = mRawPointerAxes.getRawWidth();
542 int32_t rawHeight = mRawPointerAxes.getRawHeight();
543 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
544 return std::make_optional(newViewport);
545}
546
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800547int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
548 if (resolution < 0) {
549 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
550 getDeviceName().c_str());
551 return 0;
552 }
553 return resolution;
554}
555
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800556void TouchInputMapper::initializeSizeRanges() {
557 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
558 mSizeScale = 0.0f;
559 return;
560 }
561
562 // Size of diagonal axis.
563 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
564
565 // Size factors.
566 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
567 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
568 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
569 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
570 } else {
571 mSizeScale = 0.0f;
572 }
573
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700574 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
575 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
576 .source = mSource,
577 .min = 0,
578 .max = diagonalSize,
579 .flat = 0,
580 .fuzz = 0,
581 .resolution = 0,
582 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800583
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800584 if (mRawPointerAxes.touchMajor.valid) {
585 mRawPointerAxes.touchMajor.resolution =
586 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700587 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800588 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800589
590 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700591 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800592 if (mRawPointerAxes.touchMinor.valid) {
593 mRawPointerAxes.touchMinor.resolution =
594 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700595 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800596 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800597
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700598 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
599 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
600 .source = mSource,
601 .min = 0,
602 .max = diagonalSize,
603 .flat = 0,
604 .fuzz = 0,
605 .resolution = 0,
606 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800607 if (mRawPointerAxes.toolMajor.valid) {
608 mRawPointerAxes.toolMajor.resolution =
609 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700610 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800611 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800612
613 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700614 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800615 if (mRawPointerAxes.toolMinor.valid) {
616 mRawPointerAxes.toolMinor.resolution =
617 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700618 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800619 }
620
621 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700622 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
623 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
624 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
625 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800626 } else {
627 // Support for other calibrations can be added here.
628 ALOGW("%s calibration is not supported for size ranges at the moment. "
629 "Using raw resolution instead",
630 ftl::enum_string(mCalibration.sizeCalibration).c_str());
631 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800632
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700633 mOrientedRanges.size = InputDeviceInfo::MotionRange{
634 .axis = AMOTION_EVENT_AXIS_SIZE,
635 .source = mSource,
636 .min = 0,
637 .max = 1.0,
638 .flat = 0,
639 .fuzz = 0,
640 .resolution = 0,
641 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800642}
643
644void TouchInputMapper::initializeOrientedRanges() {
645 // Configure X and Y factors.
646 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
647 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
648 mXPrecision = 1.0f / mXScale;
649 mYPrecision = 1.0f / mYScale;
650
651 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
652 mOrientedRanges.x.source = mSource;
653 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
654 mOrientedRanges.y.source = mSource;
655
656 // Scale factor for terms that are not oriented in a particular axis.
657 // If the pixels are square then xScale == yScale otherwise we fake it
658 // by choosing an average.
659 mGeometricScale = avg(mXScale, mYScale);
660
661 initializeSizeRanges();
662
663 // Pressure factors.
664 mPressureScale = 0;
665 float pressureMax = 1.0;
666 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
667 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700668 if (mCalibration.pressureScale) {
669 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800670 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
671 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
672 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
673 }
674 }
675
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700676 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
677 .axis = AMOTION_EVENT_AXIS_PRESSURE,
678 .source = mSource,
679 .min = 0,
680 .max = pressureMax,
681 .flat = 0,
682 .fuzz = 0,
683 .resolution = 0,
684 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800685
686 // Tilt
687 mTiltXCenter = 0;
688 mTiltXScale = 0;
689 mTiltYCenter = 0;
690 mTiltYScale = 0;
691 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
692 if (mHaveTilt) {
693 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
694 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
695 mTiltXScale = M_PI / 180;
696 mTiltYScale = M_PI / 180;
697
698 if (mRawPointerAxes.tiltX.resolution) {
699 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
700 }
701 if (mRawPointerAxes.tiltY.resolution) {
702 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
703 }
704
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700705 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
706 .axis = AMOTION_EVENT_AXIS_TILT,
707 .source = mSource,
708 .min = 0,
709 .max = M_PI_2,
710 .flat = 0,
711 .fuzz = 0,
712 .resolution = 0,
713 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800714 }
715
716 // Orientation
717 mOrientationScale = 0;
718 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700719 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
720 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
721 .source = mSource,
722 .min = -M_PI,
723 .max = M_PI,
724 .flat = 0,
725 .fuzz = 0,
726 .resolution = 0,
727 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800728
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800729 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
730 if (mCalibration.orientationCalibration ==
731 Calibration::OrientationCalibration::INTERPOLATED) {
732 if (mRawPointerAxes.orientation.valid) {
733 if (mRawPointerAxes.orientation.maxValue > 0) {
734 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
735 } else if (mRawPointerAxes.orientation.minValue < 0) {
736 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
737 } else {
738 mOrientationScale = 0;
739 }
740 }
741 }
742
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700743 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
744 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
745 .source = mSource,
746 .min = -M_PI_2,
747 .max = M_PI_2,
748 .flat = 0,
749 .fuzz = 0,
750 .resolution = 0,
751 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800752 }
753
754 // Distance
755 mDistanceScale = 0;
756 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
757 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700758 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800759 }
760
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700761 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800762
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700763 .axis = AMOTION_EVENT_AXIS_DISTANCE,
764 .source = mSource,
765 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
766 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
767 .flat = 0,
768 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
769 .resolution = 0,
770 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800771 }
772
773 // Compute oriented precision, scales and ranges.
774 // Note that the maximum value reported is an inclusive maximum value so it is one
775 // unit less than the total width or height of the display.
776 switch (mInputDeviceOrientation) {
777 case DISPLAY_ORIENTATION_90:
778 case DISPLAY_ORIENTATION_270:
779 mOrientedXPrecision = mYPrecision;
780 mOrientedYPrecision = mXPrecision;
781
782 mOrientedRanges.x.min = 0;
783 mOrientedRanges.x.max = mDisplayHeight - 1;
784 mOrientedRanges.x.flat = 0;
785 mOrientedRanges.x.fuzz = 0;
786 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
787
788 mOrientedRanges.y.min = 0;
789 mOrientedRanges.y.max = mDisplayWidth - 1;
790 mOrientedRanges.y.flat = 0;
791 mOrientedRanges.y.fuzz = 0;
792 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
793 break;
794
795 default:
796 mOrientedXPrecision = mXPrecision;
797 mOrientedYPrecision = mYPrecision;
798
799 mOrientedRanges.x.min = 0;
800 mOrientedRanges.x.max = mDisplayWidth - 1;
801 mOrientedRanges.x.flat = 0;
802 mOrientedRanges.x.fuzz = 0;
803 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
804
805 mOrientedRanges.y.min = 0;
806 mOrientedRanges.y.max = mDisplayHeight - 1;
807 mOrientedRanges.y.flat = 0;
808 mOrientedRanges.y.fuzz = 0;
809 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
810 break;
811 }
812}
813
Prabir Pradhan1728b212021-10-19 16:00:03 -0700814void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000815 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700816
817 resolveExternalStylusPresence();
818
819 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100820 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000821 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700822 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100823 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700824 if (hasStylus()) {
825 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000826 } else {
827 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700828 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800829 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700830 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100831 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700832 if (hasStylus()) {
833 mSource |= AINPUT_SOURCE_STYLUS;
834 }
835 if (hasExternalStylus()) {
836 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
837 }
Michael Wright227c5542020-07-02 18:30:52 +0100838 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700839 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100840 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700841 } else {
842 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100843 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700844 }
845
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000846 const std::optional<DisplayViewport> newViewportOpt = findViewport();
847
848 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700849 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
850 ALOGW("Touch device '%s' did not report support for X or Y axis! "
851 "The device will be inoperable.",
852 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100853 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000854 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700855 ALOGI("Touch device '%s' could not query the properties of its associated "
856 "display. The device will be inoperable until the display size "
857 "becomes available.",
858 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100859 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700860 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000861 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
862 getDeviceName().c_str(), getDeviceId());
863 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000864 }
865
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700866 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700867 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
868 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000869 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
870 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
871 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
872 const float rawMeanResolution =
873 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700874
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000875 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
876 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700877 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700878 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000879 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
880 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
881 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700882
Michael Wright227c5542020-07-02 18:30:52 +0100883 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700884 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700885 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
886 int32_t naturalPhysicalLeft, naturalPhysicalTop;
887 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700888
Prabir Pradhan1728b212021-10-19 16:00:03 -0700889 // Apply the inverse of the input device orientation so that the input device is
890 // configured in the same orientation as the viewport. The input device orientation will
891 // be re-applied by mInputDeviceOrientation.
892 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700893 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700894 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700895 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700896 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
897 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800898 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700899 naturalPhysicalTop = mViewport.physicalLeft;
900 naturalDeviceWidth = mViewport.deviceHeight;
901 naturalDeviceHeight = mViewport.deviceWidth;
902 break;
903 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
905 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
906 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
907 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
908 naturalDeviceWidth = mViewport.deviceWidth;
909 naturalDeviceHeight = mViewport.deviceHeight;
910 break;
911 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700912 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
913 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
914 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800915 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700916 naturalDeviceWidth = mViewport.deviceHeight;
917 naturalDeviceHeight = mViewport.deviceWidth;
918 break;
919 case DISPLAY_ORIENTATION_0:
920 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700921 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
922 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
923 naturalPhysicalLeft = mViewport.physicalLeft;
924 naturalPhysicalTop = mViewport.physicalTop;
925 naturalDeviceWidth = mViewport.deviceWidth;
926 naturalDeviceHeight = mViewport.deviceHeight;
927 break;
928 }
929
930 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
931 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
932 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
933 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
934 }
935
936 mPhysicalWidth = naturalPhysicalWidth;
937 mPhysicalHeight = naturalPhysicalHeight;
938 mPhysicalLeft = naturalPhysicalLeft;
939 mPhysicalTop = naturalPhysicalTop;
940
Prabir Pradhan1728b212021-10-19 16:00:03 -0700941 const int32_t oldDisplayWidth = mDisplayWidth;
942 const int32_t oldDisplayHeight = mDisplayHeight;
943 mDisplayWidth = naturalDeviceWidth;
944 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700945
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000946 // InputReader works in the un-rotated display coordinate space, so we don't need to do
947 // anything if the device is already orientation-aware. If the device is not
948 // orientation-aware, then we need to apply the inverse rotation of the display so that
949 // when the display rotation is applied later as a part of the per-window transform, we
950 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700951 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000952 ? DISPLAY_ORIENTATION_0
953 : getInverseRotation(mViewport.orientation);
954 // For orientation-aware devices that work in the un-rotated coordinate space, the
955 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000956 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
957 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
958 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700959
960 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700961 mInputDeviceOrientation =
962 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700963 } else {
964 mPhysicalWidth = rawWidth;
965 mPhysicalHeight = rawHeight;
966 mPhysicalLeft = 0;
967 mPhysicalTop = 0;
968
Prabir Pradhan1728b212021-10-19 16:00:03 -0700969 mDisplayWidth = rawWidth;
970 mDisplayHeight = rawHeight;
971 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700972 }
973 }
974
975 // If moving between pointer modes, need to reset some state.
976 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
977 if (deviceModeChanged) {
978 mOrientedRanges.clear();
979 }
980
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800981 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
982 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100983 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800984 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000985 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
986 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800987 if (mPointerController == nullptr) {
988 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700989 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000990 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800991 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
992 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700993 } else {
lilinnandef700b2022-06-17 19:32:01 +0800994 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
995 !mConfig.showTouches) {
996 mPointerController->clearSpots();
997 }
Michael Wright17db18e2020-06-26 20:51:44 +0100998 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700999 }
1000
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001001 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001002 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1003 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001004 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1005 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001006
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001007 configureVirtualKeys();
1008
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001009 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001010
1011 // Location
1012 updateAffineTransformation();
1013
Michael Wright227c5542020-07-02 18:30:52 +01001014 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001015 // Compute pointer gesture detection parameters.
1016 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001017 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001018
1019 // Scale movements such that one whole swipe of the touch pad covers a
1020 // given area relative to the diagonal size of the display when no acceleration
1021 // is applied.
1022 // Assume that the touch pad has a square aspect ratio such that movements in
1023 // X and Y of the same number of raw units cover the same physical distance.
1024 mPointerXMovementScale =
1025 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1026 mPointerYMovementScale = mPointerXMovementScale;
1027
1028 // Scale zooms to cover a smaller range of the display than movements do.
1029 // This value determines the area around the pointer that is affected by freeform
1030 // pointer gestures.
1031 mPointerXZoomScale =
1032 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1033 mPointerYZoomScale = mPointerXZoomScale;
1034
HQ Liue6983c72022-04-19 22:14:56 +00001035 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1036 // axis is non positive value.
1037 const float minFreeformGestureWidth =
1038 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1039
1040 mPointerGestureMaxSwipeWidth =
1041 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1042 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001043 }
1044
1045 // Inform the dispatcher about the changes.
1046 *outResetNeeded = true;
1047 bumpGeneration();
1048 }
1049}
1050
Prabir Pradhan1728b212021-10-19 16:00:03 -07001051void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001052 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001053 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1054 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001055 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1056 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1057 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1058 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001059 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001060}
1061
1062void TouchInputMapper::configureVirtualKeys() {
1063 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001064 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001065
1066 mVirtualKeys.clear();
1067
1068 if (virtualKeyDefinitions.size() == 0) {
1069 return;
1070 }
1071
1072 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1073 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1074 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1075 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1076
1077 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1078 VirtualKey virtualKey;
1079
1080 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1081 int32_t keyCode;
1082 int32_t dummyKeyMetaState;
1083 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001084 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1085 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1087 continue; // drop the key
1088 }
1089
1090 virtualKey.keyCode = keyCode;
1091 virtualKey.flags = flags;
1092
1093 // convert the key definition's display coordinates into touch coordinates for a hit box
1094 int32_t halfWidth = virtualKeyDefinition.width / 2;
1095 int32_t halfHeight = virtualKeyDefinition.height / 2;
1096
1097 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001098 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001099 touchScreenLeft;
1100 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001101 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001102 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001103 virtualKey.hitTop =
1104 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001106 virtualKey.hitBottom =
1107 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001108 touchScreenTop;
1109 mVirtualKeys.push_back(virtualKey);
1110 }
1111}
1112
1113void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1114 if (!mVirtualKeys.empty()) {
1115 dump += INDENT3 "Virtual Keys:\n";
1116
1117 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1118 const VirtualKey& virtualKey = mVirtualKeys[i];
1119 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1120 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1121 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1122 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1123 }
1124 }
1125}
1126
1127void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001128 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001129 Calibration& out = mCalibration;
1130
1131 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001132 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001133 std::string sizeCalibrationString;
1134 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001146 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 }
1148 }
1149
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001150 float sizeScale;
1151
1152 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1153 out.sizeScale = sizeScale;
1154 }
1155 float sizeBias;
1156 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1157 out.sizeBias = sizeBias;
1158 }
1159 bool sizeIsSummed;
1160 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1161 out.sizeIsSummed = sizeIsSummed;
1162 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001163
1164 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001165 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001166 std::string pressureCalibrationString;
1167 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (pressureCalibrationString != "default") {
1175 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001176 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 }
1178 }
1179
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001180 float pressureScale;
1181 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1182 out.pressureScale = pressureScale;
1183 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184
1185 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001186 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001187 std::string orientationCalibrationString;
1188 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001194 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 } else if (orientationCalibrationString != "default") {
1196 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001197 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 }
1199 }
1200
1201 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001203 std::string distanceCalibrationString;
1204 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 } else if (distanceCalibrationString != "default") {
1210 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001211 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 }
1213 }
1214
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001215 float distanceScale;
1216 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1217 out.distanceScale = distanceScale;
1218 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219
Michael Wright227c5542020-07-02 18:30:52 +01001220 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001221 std::string coverageCalibrationString;
1222 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001226 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 } else if (coverageCalibrationString != "default") {
1228 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001229 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 }
1231 }
1232}
1233
1234void TouchInputMapper::resolveCalibration() {
1235 // Size
1236 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001237 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1238 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 }
1240 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001241 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 }
1243
1244 // Pressure
1245 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001246 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1247 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001250 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 }
1252
1253 // Orientation
1254 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001255 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1256 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001259 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 }
1261
1262 // Distance
1263 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001264 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1265 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001268 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270
1271 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001272 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1273 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274 }
1275}
1276
1277void TouchInputMapper::dumpCalibration(std::string& dump) {
1278 dump += INDENT3 "Calibration:\n";
1279
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001280 dump += INDENT4 "touch.size.calibration: ";
1281 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001283 if (mCalibration.sizeScale) {
1284 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 }
1286
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001287 if (mCalibration.sizeBias) {
1288 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 }
1290
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001291 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001293 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 }
1295
1296 // Pressure
1297 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001298 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 dump += INDENT4 "touch.pressure.calibration: none\n";
1300 break;
Michael Wright227c5542020-07-02 18:30:52 +01001301 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001302 dump += INDENT4 "touch.pressure.calibration: physical\n";
1303 break;
Michael Wright227c5542020-07-02 18:30:52 +01001304 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1306 break;
1307 default:
1308 ALOG_ASSERT(false);
1309 }
1310
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001311 if (mCalibration.pressureScale) {
1312 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 }
1314
1315 // Orientation
1316 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001317 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.orientation.calibration: none\n";
1319 break;
Michael Wright227c5542020-07-02 18:30:52 +01001320 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001321 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1322 break;
Michael Wright227c5542020-07-02 18:30:52 +01001323 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 dump += INDENT4 "touch.orientation.calibration: vector\n";
1325 break;
1326 default:
1327 ALOG_ASSERT(false);
1328 }
1329
1330 // Distance
1331 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001332 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333 dump += INDENT4 "touch.distance.calibration: none\n";
1334 break;
Michael Wright227c5542020-07-02 18:30:52 +01001335 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001336 dump += INDENT4 "touch.distance.calibration: scaled\n";
1337 break;
1338 default:
1339 ALOG_ASSERT(false);
1340 }
1341
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001342 if (mCalibration.distanceScale) {
1343 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 }
1345
1346 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001347 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001348 dump += INDENT4 "touch.coverage.calibration: none\n";
1349 break;
Michael Wright227c5542020-07-02 18:30:52 +01001350 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001351 dump += INDENT4 "touch.coverage.calibration: box\n";
1352 break;
1353 default:
1354 ALOG_ASSERT(false);
1355 }
1356}
1357
1358void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1359 dump += INDENT3 "Affine Transformation:\n";
1360
1361 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1362 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1363 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1364 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1365 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1366 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1367}
1368
1369void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001370 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001371 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001372}
1373
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001374std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001375 std::list<NotifyArgs> out = cancelTouch(when, when);
1376 updateTouchSpots();
1377
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001378 mCursorButtonAccumulator.reset(getDeviceContext());
1379 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001380 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001381
1382 mPointerVelocityControl.reset();
1383 mWheelXVelocityControl.reset();
1384 mWheelYVelocityControl.reset();
1385
1386 mRawStatesPending.clear();
1387 mCurrentRawState.clear();
1388 mCurrentCookedState.clear();
1389 mLastRawState.clear();
1390 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001391 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001392 mSentHoverEnter = false;
1393 mHavePointerIds = false;
1394 mCurrentMotionAborted = false;
1395 mDownTime = 0;
1396
1397 mCurrentVirtualKey.down = false;
1398
1399 mPointerGesture.reset();
1400 mPointerSimple.reset();
1401 resetExternalStylus();
1402
1403 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001404 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001405 mPointerController->clearSpots();
1406 }
1407
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001408 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001409}
1410
1411void TouchInputMapper::resetExternalStylus() {
1412 mExternalStylusState.clear();
1413 mExternalStylusId = -1;
1414 mExternalStylusFusionTimeout = LLONG_MAX;
1415 mExternalStylusDataPending = false;
1416}
1417
1418void TouchInputMapper::clearStylusDataPendingFlags() {
1419 mExternalStylusDataPending = false;
1420 mExternalStylusFusionTimeout = LLONG_MAX;
1421}
1422
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001423std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001424 mCursorButtonAccumulator.process(rawEvent);
1425 mCursorScrollAccumulator.process(rawEvent);
1426 mTouchButtonAccumulator.process(rawEvent);
1427
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001428 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001429 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001430 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001432 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001433}
1434
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001435std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1436 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001437 if (mDeviceMode == DeviceMode::DISABLED) {
1438 // Only save the last pending state when the device is disabled.
1439 mRawStatesPending.clear();
1440 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001441 // Push a new state.
1442 mRawStatesPending.emplace_back();
1443
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001444 RawState& next = mRawStatesPending.back();
1445 next.clear();
1446 next.when = when;
1447 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001448
1449 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001450 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1452
1453 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001454 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1455 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456 mCursorScrollAccumulator.finishSync();
1457
1458 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001459 syncTouch(when, &next);
1460
1461 // The last RawState is the actually second to last, since we just added a new state
1462 const RawState& last =
1463 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001464
1465 // Assign pointer ids.
1466 if (!mHavePointerIds) {
1467 assignPointerIds(last, next);
1468 }
1469
Harry Cutts45483602022-08-24 14:36:48 +00001470 ALOGD_IF(DEBUG_RAW_EVENTS,
1471 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1472 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1473 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1474 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1475 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1476 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001477
Arthur Hung9ad18942021-06-19 02:04:46 +00001478 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1479 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1480 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1481 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1482 next.rawPointerData.hoveringIdBits.value);
1483 }
1484
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001485 out += processRawTouches(false /*timeout*/);
1486 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001487}
1488
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001489std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1490 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001491 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001492 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001493 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001494 }
1495
1496 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1497 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1498 // touching the current state will only observe the events that have been dispatched to the
1499 // rest of the pipeline.
1500 const size_t N = mRawStatesPending.size();
1501 size_t count;
1502 for (count = 0; count < N; count++) {
1503 const RawState& next = mRawStatesPending[count];
1504
1505 // A failure to assign the stylus id means that we're waiting on stylus data
1506 // and so should defer the rest of the pipeline.
1507 if (assignExternalStylusId(next, timeout)) {
1508 break;
1509 }
1510
1511 // All ready to go.
1512 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001513 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001514 if (mCurrentRawState.when < mLastRawState.when) {
1515 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001516 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001518 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001519 }
1520 if (count != 0) {
1521 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1522 }
1523
1524 if (mExternalStylusDataPending) {
1525 if (timeout) {
1526 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1527 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001528 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001529 ALOGD_IF(DEBUG_STYLUS_FUSION,
1530 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001531 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001532 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001533 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1534 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1535 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1536 }
1537 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001538 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001539}
1540
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001541std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1542 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001543 // Always start with a clean state.
1544 mCurrentCookedState.clear();
1545
1546 // Apply stylus buttons to current raw state.
1547 applyExternalStylusButtonState(when);
1548
1549 // Handle policy on initial down or hover events.
1550 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1551 mCurrentRawState.rawPointerData.pointerCount != 0;
1552
1553 uint32_t policyFlags = 0;
1554 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1555 if (initialDown || buttonsPressed) {
1556 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001557 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001558 getContext()->fadePointer();
1559 }
1560
1561 if (mParameters.wake) {
1562 policyFlags |= POLICY_FLAG_WAKE;
1563 }
1564 }
1565
1566 // Consume raw off-screen touches before cooking pointer data.
1567 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001568 bool consumed;
1569 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1570 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001571 mCurrentRawState.rawPointerData.clear();
1572 }
1573
1574 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1575 // with cooked pointer data that has the same ids and indices as the raw data.
1576 // The following code can use either the raw or cooked data, as needed.
1577 cookPointerData();
1578
1579 // Apply stylus pressure to current cooked state.
1580 applyExternalStylusTouchState(when);
1581
1582 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001583 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1584 mSource, mViewport.displayId, policyFlags,
1585 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001586
1587 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001588 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001589 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1590 uint32_t id = idBits.clearFirstMarkedBit();
1591 const RawPointerData::Pointer& pointer =
1592 mCurrentRawState.rawPointerData.pointerForId(id);
1593 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1594 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1595 mCurrentCookedState.stylusIdBits.markBit(id);
1596 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1597 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1598 mCurrentCookedState.fingerIdBits.markBit(id);
1599 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1600 mCurrentCookedState.mouseIdBits.markBit(id);
1601 }
1602 }
1603 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1604 uint32_t id = idBits.clearFirstMarkedBit();
1605 const RawPointerData::Pointer& pointer =
1606 mCurrentRawState.rawPointerData.pointerForId(id);
1607 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1608 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1609 mCurrentCookedState.stylusIdBits.markBit(id);
1610 }
1611 }
1612
1613 // Stylus takes precedence over all tools, then mouse, then finger.
1614 PointerUsage pointerUsage = mPointerUsage;
1615 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1616 mCurrentCookedState.mouseIdBits.clear();
1617 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001618 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001619 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1620 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001621 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001622 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1623 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001624 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625 }
1626
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001627 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001630 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001631 out += dispatchButtonRelease(when, readTime, policyFlags);
1632 out += dispatchHoverExit(when, readTime, policyFlags);
1633 out += dispatchTouches(when, readTime, policyFlags);
1634 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1635 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636 }
1637
1638 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1639 mCurrentMotionAborted = false;
1640 }
1641 }
1642
1643 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001644 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1645 mSource, mViewport.displayId, policyFlags,
1646 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647
1648 // Clear some transient state.
1649 mCurrentRawState.rawVScroll = 0;
1650 mCurrentRawState.rawHScroll = 0;
1651
1652 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001653 mLastRawState = mCurrentRawState;
1654 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001655 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001656}
1657
Garfield Tanc734e4f2021-01-15 20:01:39 -08001658void TouchInputMapper::updateTouchSpots() {
1659 if (!mConfig.showTouches || mPointerController == nullptr) {
1660 return;
1661 }
1662
1663 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1664 // clear touch spots.
1665 if (mDeviceMode != DeviceMode::DIRECT &&
1666 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1667 return;
1668 }
1669
1670 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1671 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1672
1673 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001674 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1675 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001676 mCurrentCookedState.cookedPointerData.touchingIdBits,
1677 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001678}
1679
1680bool TouchInputMapper::isTouchScreen() {
1681 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1682 mParameters.hasAssociatedDisplay;
1683}
1684
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001685void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001686 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001687 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1688 }
1689}
1690
1691void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1692 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1693 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1694
1695 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1696 float pressure = mExternalStylusState.pressure;
1697 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1698 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1699 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1700 }
1701 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1702 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1703
1704 PointerProperties& properties =
1705 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1706 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1707 properties.toolType = mExternalStylusState.toolType;
1708 }
1709 }
1710}
1711
1712bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001713 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714 return false;
1715 }
1716
1717 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1718 state.rawPointerData.pointerCount != 0;
1719 if (initialDown) {
1720 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001721 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001722 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1723 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001724 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001725 resetExternalStylus();
1726 } else {
1727 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1728 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1729 }
Harry Cutts45483602022-08-24 14:36:48 +00001730 ALOGD_IF(DEBUG_STYLUS_FUSION,
1731 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1732 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001733 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1734 return true;
1735 }
1736 }
1737
1738 // Check if the stylus pointer has gone up.
1739 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001740 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001741 mExternalStylusId = -1;
1742 }
1743
1744 return false;
1745}
1746
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001747std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1748 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001749 if (mDeviceMode == DeviceMode::POINTER) {
1750 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001751 // Since this is a synthetic event, we can consider its latency to be zero
1752 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001753 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001754 }
Michael Wright227c5542020-07-02 18:30:52 +01001755 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001756 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001757 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001758 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1759 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1760 }
1761 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001762 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001763}
1764
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001765std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1766 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001767 mExternalStylusState.copyFrom(state);
1768 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1769 // We're either in the middle of a fused stream of data or we're waiting on data before
1770 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1771 // data.
1772 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001773 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001774 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001775 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001776}
1777
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001778std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1779 uint32_t policyFlags, bool& outConsumed) {
1780 outConsumed = false;
1781 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001782 // Check for release of a virtual key.
1783 if (mCurrentVirtualKey.down) {
1784 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1785 // Pointer went up while virtual key was down.
1786 mCurrentVirtualKey.down = false;
1787 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001788 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1789 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1790 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001791 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1792 AKEY_EVENT_FLAG_FROM_SYSTEM |
1793 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001794 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001795 outConsumed = true;
1796 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001797 }
1798
1799 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1800 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1801 const RawPointerData::Pointer& pointer =
1802 mCurrentRawState.rawPointerData.pointerForId(id);
1803 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1804 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1805 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001806 outConsumed = true;
1807 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001808 }
1809 }
1810
1811 // Pointer left virtual key area or another pointer also went down.
1812 // Send key cancellation but do not consume the touch yet.
1813 // This is useful when the user swipes through from the virtual key area
1814 // into the main display surface.
1815 mCurrentVirtualKey.down = false;
1816 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001817 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1818 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001819 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1820 AKEY_EVENT_FLAG_FROM_SYSTEM |
1821 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1822 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001823 }
1824 }
1825
1826 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1827 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1828 // Pointer just went down. Check for virtual key press or off-screen touches.
1829 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1830 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001831 // Skip checking whether the pointer is inside the physical frame if the device is in
1832 // unscaled mode.
1833 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1834 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001835 // If exactly one pointer went down, check for virtual key hit.
1836 // Otherwise we will drop the entire stroke.
1837 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1838 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1839 if (virtualKey) {
1840 mCurrentVirtualKey.down = true;
1841 mCurrentVirtualKey.downTime = when;
1842 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1843 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1844 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001845 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1846 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001847
1848 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001849 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1850 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1851 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001852 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1853 AKEY_EVENT_ACTION_DOWN,
1854 AKEY_EVENT_FLAG_FROM_SYSTEM |
1855 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001856 }
1857 }
1858 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001859 outConsumed = true;
1860 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001861 }
1862 }
1863
1864 // Disable all virtual key touches that happen within a short time interval of the
1865 // most recent touch within the screen area. The idea is to filter out stray
1866 // virtual key presses when interacting with the touch screen.
1867 //
1868 // Problems we're trying to solve:
1869 //
1870 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1871 // virtual key area that is implemented by a separate touch panel and accidentally
1872 // triggers a virtual key.
1873 //
1874 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1875 // area and accidentally triggers a virtual key. This often happens when virtual keys
1876 // are layed out below the screen near to where the on screen keyboard's space bar
1877 // is displayed.
1878 if (mConfig.virtualKeyQuietTime > 0 &&
1879 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001880 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001881 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001882 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001883}
1884
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001885NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1886 uint32_t policyFlags, int32_t keyEventAction,
1887 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001888 int32_t keyCode = mCurrentVirtualKey.keyCode;
1889 int32_t scanCode = mCurrentVirtualKey.scanCode;
1890 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001891 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001892 policyFlags |= POLICY_FLAG_VIRTUAL;
1893
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001894 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1895 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1896 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001897}
1898
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001899std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1900 uint32_t policyFlags) {
1901 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001902 if (mCurrentMotionAborted) {
1903 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001904 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001905 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001906 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1907 if (!currentIdBits.isEmpty()) {
1908 int32_t metaState = getContext()->getGlobalMetaState();
1909 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001910 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001911 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1912 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001913 mCurrentCookedState.cookedPointerData.pointerProperties,
1914 mCurrentCookedState.cookedPointerData.pointerCoords,
1915 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1916 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1917 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001918 mCurrentMotionAborted = true;
1919 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921}
1922
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001923// Updates pointer coords and properties for pointers with specified ids that have moved.
1924// Returns true if any of them changed.
1925static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1926 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1927 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1928 BitSet32 idBits) {
1929 bool changed = false;
1930 while (!idBits.isEmpty()) {
1931 uint32_t id = idBits.clearFirstMarkedBit();
1932 uint32_t inIndex = inIdToIndex[id];
1933 uint32_t outIndex = outIdToIndex[id];
1934
1935 const PointerProperties& curInProperties = inProperties[inIndex];
1936 const PointerCoords& curInCoords = inCoords[inIndex];
1937 PointerProperties& curOutProperties = outProperties[outIndex];
1938 PointerCoords& curOutCoords = outCoords[outIndex];
1939
1940 if (curInProperties != curOutProperties) {
1941 curOutProperties.copyFrom(curInProperties);
1942 changed = true;
1943 }
1944
1945 if (curInCoords != curOutCoords) {
1946 curOutCoords.copyFrom(curInCoords);
1947 changed = true;
1948 }
1949 }
1950 return changed;
1951}
1952
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001953std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1954 uint32_t policyFlags) {
1955 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001956 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1957 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1958 int32_t metaState = getContext()->getGlobalMetaState();
1959 int32_t buttonState = mCurrentCookedState.buttonState;
1960
1961 if (currentIdBits == lastIdBits) {
1962 if (!currentIdBits.isEmpty()) {
1963 // No pointer id changes so this is a move event.
1964 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001965 out.push_back(
1966 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1967 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1968 mCurrentCookedState.cookedPointerData.pointerProperties,
1969 mCurrentCookedState.cookedPointerData.pointerCoords,
1970 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1971 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1972 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001973 }
1974 } else {
1975 // There may be pointers going up and pointers going down and pointers moving
1976 // all at the same time.
1977 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1978 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1979 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1980 BitSet32 dispatchedIdBits(lastIdBits.value);
1981
1982 // Update last coordinates of pointers that have moved so that we observe the new
1983 // pointer positions at the same time as other pointers that have just gone up.
1984 bool moveNeeded =
1985 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1986 mCurrentCookedState.cookedPointerData.pointerCoords,
1987 mCurrentCookedState.cookedPointerData.idToIndex,
1988 mLastCookedState.cookedPointerData.pointerProperties,
1989 mLastCookedState.cookedPointerData.pointerCoords,
1990 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1991 if (buttonState != mLastCookedState.buttonState) {
1992 moveNeeded = true;
1993 }
1994
1995 // Dispatch pointer up events.
1996 while (!upIdBits.isEmpty()) {
1997 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001998 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001999 if (isCanceled) {
2000 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2001 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002002 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2003 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2004 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2005 buttonState, 0,
2006 mLastCookedState.cookedPointerData.pointerProperties,
2007 mLastCookedState.cookedPointerData.pointerCoords,
2008 mLastCookedState.cookedPointerData.idToIndex,
2009 dispatchedIdBits, upId, mOrientedXPrecision,
2010 mOrientedYPrecision, mDownTime,
2011 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002012 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002013 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002014 }
2015
2016 // Dispatch move events if any of the remaining pointers moved from their old locations.
2017 // Although applications receive new locations as part of individual pointer up
2018 // events, they do not generally handle them except when presented in a move event.
2019 if (moveNeeded && !moveIdBits.isEmpty()) {
2020 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002021 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2022 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2023 mCurrentCookedState.cookedPointerData.pointerProperties,
2024 mCurrentCookedState.cookedPointerData.pointerCoords,
2025 mCurrentCookedState.cookedPointerData.idToIndex,
2026 dispatchedIdBits, -1, mOrientedXPrecision,
2027 mOrientedYPrecision, mDownTime,
2028 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002029 }
2030
2031 // Dispatch pointer down events using the new pointer locations.
2032 while (!downIdBits.isEmpty()) {
2033 uint32_t downId = downIdBits.clearFirstMarkedBit();
2034 dispatchedIdBits.markBit(downId);
2035
2036 if (dispatchedIdBits.count() == 1) {
2037 // First pointer is going down. Set down time.
2038 mDownTime = when;
2039 }
2040
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002041 out.push_back(
2042 dispatchMotion(when, readTime, policyFlags, mSource,
2043 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2044 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2045 mCurrentCookedState.cookedPointerData.pointerCoords,
2046 mCurrentCookedState.cookedPointerData.idToIndex,
2047 dispatchedIdBits, downId, mOrientedXPrecision,
2048 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002049 }
2050 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002051 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002052}
2053
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002054std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2055 uint32_t policyFlags) {
2056 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002057 if (mSentHoverEnter &&
2058 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2059 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2060 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002061 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2062 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2063 mLastCookedState.buttonState, 0,
2064 mLastCookedState.cookedPointerData.pointerProperties,
2065 mLastCookedState.cookedPointerData.pointerCoords,
2066 mLastCookedState.cookedPointerData.idToIndex,
2067 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2068 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2069 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002070 mSentHoverEnter = false;
2071 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002072 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002073}
2074
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002075std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2076 uint32_t policyFlags) {
2077 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002078 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2079 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2080 int32_t metaState = getContext()->getGlobalMetaState();
2081 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002082 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2083 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2084 mCurrentRawState.buttonState, 0,
2085 mCurrentCookedState.cookedPointerData.pointerProperties,
2086 mCurrentCookedState.cookedPointerData.pointerCoords,
2087 mCurrentCookedState.cookedPointerData.idToIndex,
2088 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2089 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2090 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002091 mSentHoverEnter = true;
2092 }
2093
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002094 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2095 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2096 mCurrentRawState.buttonState, 0,
2097 mCurrentCookedState.cookedPointerData.pointerProperties,
2098 mCurrentCookedState.cookedPointerData.pointerCoords,
2099 mCurrentCookedState.cookedPointerData.idToIndex,
2100 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2101 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2102 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002103 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002104 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002105}
2106
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002107std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2108 uint32_t policyFlags) {
2109 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2111 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2112 const int32_t metaState = getContext()->getGlobalMetaState();
2113 int32_t buttonState = mLastCookedState.buttonState;
2114 while (!releasedButtons.isEmpty()) {
2115 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2116 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002117 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2118 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2119 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002120 mLastCookedState.cookedPointerData.pointerProperties,
2121 mLastCookedState.cookedPointerData.pointerCoords,
2122 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002123 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2124 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002125 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002126 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002127}
2128
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002129std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2130 uint32_t policyFlags) {
2131 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002132 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2133 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2134 const int32_t metaState = getContext()->getGlobalMetaState();
2135 int32_t buttonState = mLastCookedState.buttonState;
2136 while (!pressedButtons.isEmpty()) {
2137 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2138 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002139 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2140 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2141 buttonState, 0,
2142 mCurrentCookedState.cookedPointerData.pointerProperties,
2143 mCurrentCookedState.cookedPointerData.pointerCoords,
2144 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2145 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2146 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002147 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002148 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002149}
2150
2151const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2152 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2153 return cookedPointerData.touchingIdBits;
2154 }
2155 return cookedPointerData.hoveringIdBits;
2156}
2157
2158void TouchInputMapper::cookPointerData() {
2159 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2160
2161 mCurrentCookedState.cookedPointerData.clear();
2162 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2163 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2164 mCurrentRawState.rawPointerData.hoveringIdBits;
2165 mCurrentCookedState.cookedPointerData.touchingIdBits =
2166 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002167 mCurrentCookedState.cookedPointerData.canceledIdBits =
2168 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002169
2170 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2171 mCurrentCookedState.buttonState = 0;
2172 } else {
2173 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2174 }
2175
2176 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002177 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002178 for (uint32_t i = 0; i < currentPointerCount; i++) {
2179 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2180
2181 // Size
2182 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2183 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002184 case Calibration::SizeCalibration::GEOMETRIC:
2185 case Calibration::SizeCalibration::DIAMETER:
2186 case Calibration::SizeCalibration::BOX:
2187 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002188 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2189 touchMajor = in.touchMajor;
2190 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2191 toolMajor = in.toolMajor;
2192 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2193 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2194 : in.touchMajor;
2195 } else if (mRawPointerAxes.touchMajor.valid) {
2196 toolMajor = touchMajor = in.touchMajor;
2197 toolMinor = touchMinor =
2198 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2199 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2200 : in.touchMajor;
2201 } else if (mRawPointerAxes.toolMajor.valid) {
2202 touchMajor = toolMajor = in.toolMajor;
2203 touchMinor = toolMinor =
2204 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2205 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2206 : in.toolMajor;
2207 } else {
2208 ALOG_ASSERT(false,
2209 "No touch or tool axes. "
2210 "Size calibration should have been resolved to NONE.");
2211 touchMajor = 0;
2212 touchMinor = 0;
2213 toolMajor = 0;
2214 toolMinor = 0;
2215 size = 0;
2216 }
2217
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002218 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002219 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2220 if (touchingCount > 1) {
2221 touchMajor /= touchingCount;
2222 touchMinor /= touchingCount;
2223 toolMajor /= touchingCount;
2224 toolMinor /= touchingCount;
2225 size /= touchingCount;
2226 }
2227 }
2228
Michael Wright227c5542020-07-02 18:30:52 +01002229 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002230 touchMajor *= mGeometricScale;
2231 touchMinor *= mGeometricScale;
2232 toolMajor *= mGeometricScale;
2233 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002234 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002235 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2236 touchMinor = touchMajor;
2237 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2238 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002239 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002240 touchMinor = touchMajor;
2241 toolMinor = toolMajor;
2242 }
2243
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002244 mCalibration.applySizeScaleAndBias(touchMajor);
2245 mCalibration.applySizeScaleAndBias(touchMinor);
2246 mCalibration.applySizeScaleAndBias(toolMajor);
2247 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002248 size *= mSizeScale;
2249 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002250 case Calibration::SizeCalibration::DEFAULT:
2251 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2252 break;
2253 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002254 touchMajor = 0;
2255 touchMinor = 0;
2256 toolMajor = 0;
2257 toolMinor = 0;
2258 size = 0;
2259 break;
2260 }
2261
2262 // Pressure
2263 float pressure;
2264 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002265 case Calibration::PressureCalibration::PHYSICAL:
2266 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002267 pressure = in.pressure * mPressureScale;
2268 break;
2269 default:
2270 pressure = in.isHovering ? 0 : 1;
2271 break;
2272 }
2273
2274 // Tilt and Orientation
2275 float tilt;
2276 float orientation;
2277 if (mHaveTilt) {
2278 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2279 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2280 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2281 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2282 } else {
2283 tilt = 0;
2284
2285 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002286 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002287 orientation = in.orientation * mOrientationScale;
2288 break;
Michael Wright227c5542020-07-02 18:30:52 +01002289 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002290 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2291 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2292 if (c1 != 0 || c2 != 0) {
2293 orientation = atan2f(c1, c2) * 0.5f;
2294 float confidence = hypotf(c1, c2);
2295 float scale = 1.0f + confidence / 16.0f;
2296 touchMajor *= scale;
2297 touchMinor /= scale;
2298 toolMajor *= scale;
2299 toolMinor /= scale;
2300 } else {
2301 orientation = 0;
2302 }
2303 break;
2304 }
2305 default:
2306 orientation = 0;
2307 }
2308 }
2309
2310 // Distance
2311 float distance;
2312 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002313 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002314 distance = in.distance * mDistanceScale;
2315 break;
2316 default:
2317 distance = 0;
2318 }
2319
2320 // Coverage
2321 int32_t rawLeft, rawTop, rawRight, rawBottom;
2322 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002323 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002324 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2325 rawRight = in.toolMinor & 0x0000ffff;
2326 rawBottom = in.toolMajor & 0x0000ffff;
2327 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2328 break;
2329 default:
2330 rawLeft = rawTop = rawRight = rawBottom = 0;
2331 break;
2332 }
2333
2334 // Adjust X,Y coords for device calibration
2335 // TODO: Adjust coverage coords?
2336 float xTransformed = in.x, yTransformed = in.y;
2337 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002338 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339
Prabir Pradhan1728b212021-10-19 16:00:03 -07002340 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002341 float left, top, right, bottom;
2342
Prabir Pradhan1728b212021-10-19 16:00:03 -07002343 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002345 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2346 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2347 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2348 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002350 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002352 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353 }
2354 break;
2355 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2357 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002358 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2359 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002360 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002361 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002363 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002364 }
2365 break;
2366 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2368 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002369 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2370 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002372 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002374 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 }
2376 break;
2377 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002378 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2379 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2380 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2381 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 break;
2383 }
2384
2385 // Write output coords.
2386 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2387 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002388 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2389 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2391 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2392 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2393 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2394 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2395 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2396 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002397 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2400 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2402 } else {
2403 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2404 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2405 }
2406
Chris Ye364fdb52020-08-05 15:07:56 -07002407 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002408 uint32_t id = in.id;
2409 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2410 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2411 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2412 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2413 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2414 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2415 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2416 }
2417
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 // Write output properties.
2419 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 properties.clear();
2421 properties.id = id;
2422 properties.toolType = in.toolType;
2423
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002424 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002426 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 }
2428}
2429
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002430std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2431 uint32_t policyFlags,
2432 PointerUsage pointerUsage) {
2433 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002435 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 mPointerUsage = pointerUsage;
2437 }
2438
2439 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002440 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002441 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 break;
Michael Wright227c5542020-07-02 18:30:52 +01002443 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002444 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 break;
Michael Wright227c5542020-07-02 18:30:52 +01002446 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002447 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 break;
Michael Wright227c5542020-07-02 18:30:52 +01002449 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 break;
2451 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002452 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453}
2454
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002455std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2456 uint32_t policyFlags) {
2457 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002459 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002460 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 break;
Michael Wright227c5542020-07-02 18:30:52 +01002462 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002463 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 break;
Michael Wright227c5542020-07-02 18:30:52 +01002465 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002466 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 break;
Michael Wright227c5542020-07-02 18:30:52 +01002468 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 break;
2470 }
2471
Michael Wright227c5542020-07-02 18:30:52 +01002472 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474}
2475
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002476std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2477 uint32_t policyFlags,
2478 bool isTimeout) {
2479 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 // Update current gesture coordinates.
2481 bool cancelPreviousGesture, finishPreviousGesture;
2482 bool sendEvents =
2483 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2484 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002485 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 }
2487 if (finishPreviousGesture) {
2488 cancelPreviousGesture = false;
2489 }
2490
2491 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002492 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002493 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 if (finishPreviousGesture || cancelPreviousGesture) {
2495 mPointerController->clearSpots();
2496 }
2497
Michael Wright227c5542020-07-02 18:30:52 +01002498 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002499 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2500 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002501 mPointerGesture.currentGestureIdBits,
2502 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 }
2504 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002505 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002506 }
2507
2508 // Show or hide the pointer if needed.
2509 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002510 case PointerGesture::Mode::NEUTRAL:
2511 case PointerGesture::Mode::QUIET:
2512 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2513 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002515 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516 }
2517 break;
Michael Wright227c5542020-07-02 18:30:52 +01002518 case PointerGesture::Mode::TAP:
2519 case PointerGesture::Mode::TAP_DRAG:
2520 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2521 case PointerGesture::Mode::HOVER:
2522 case PointerGesture::Mode::PRESS:
2523 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 // Unfade the pointer when the current gesture manipulates the
2525 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002526 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002527 break;
Michael Wright227c5542020-07-02 18:30:52 +01002528 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002529 // Fade the pointer when the current gesture manipulates a different
2530 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002531 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002532 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002533 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002534 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535 }
2536 break;
2537 }
2538
2539 // Send events!
2540 int32_t metaState = getContext()->getGlobalMetaState();
2541 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002542 const MotionClassification classification =
2543 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2544 ? MotionClassification::TWO_FINGER_SWIPE
2545 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002546
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002547 uint32_t flags = 0;
2548
2549 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2550 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2551 }
2552
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 // Update last coordinates of pointers that have moved so that we observe the new
2554 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002555 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2556 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2557 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2558 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2559 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2560 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002561 bool moveNeeded = false;
2562 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2563 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2564 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2565 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2566 mPointerGesture.lastGestureIdBits.value);
2567 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2568 mPointerGesture.currentGestureCoords,
2569 mPointerGesture.currentGestureIdToIndex,
2570 mPointerGesture.lastGestureProperties,
2571 mPointerGesture.lastGestureCoords,
2572 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2573 if (buttonState != mLastCookedState.buttonState) {
2574 moveNeeded = true;
2575 }
2576 }
2577
2578 // Send motion events for all pointers that went up or were canceled.
2579 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2580 if (!dispatchedGestureIdBits.isEmpty()) {
2581 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002582 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002583 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002584 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002585 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2586 mPointerGesture.lastGestureProperties,
2587 mPointerGesture.lastGestureCoords,
2588 mPointerGesture.lastGestureIdToIndex,
2589 dispatchedGestureIdBits, -1, 0, 0,
2590 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591
2592 dispatchedGestureIdBits.clear();
2593 } else {
2594 BitSet32 upGestureIdBits;
2595 if (finishPreviousGesture) {
2596 upGestureIdBits = dispatchedGestureIdBits;
2597 } else {
2598 upGestureIdBits.value =
2599 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2600 }
2601 while (!upGestureIdBits.isEmpty()) {
2602 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2603
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002604 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2605 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2606 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2607 mPointerGesture.lastGestureProperties,
2608 mPointerGesture.lastGestureCoords,
2609 mPointerGesture.lastGestureIdToIndex,
2610 dispatchedGestureIdBits, id, 0, 0,
2611 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002612
2613 dispatchedGestureIdBits.clearBit(id);
2614 }
2615 }
2616 }
2617
2618 // Send motion events for all pointers that moved.
2619 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002620 out.push_back(
2621 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2622 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2623 mPointerGesture.currentGestureProperties,
2624 mPointerGesture.currentGestureCoords,
2625 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2626 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002627 }
2628
2629 // Send motion events for all pointers that went down.
2630 if (down) {
2631 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2632 ~dispatchedGestureIdBits.value);
2633 while (!downGestureIdBits.isEmpty()) {
2634 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2635 dispatchedGestureIdBits.markBit(id);
2636
2637 if (dispatchedGestureIdBits.count() == 1) {
2638 mPointerGesture.downTime = when;
2639 }
2640
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002641 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2642 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2643 buttonState, 0, mPointerGesture.currentGestureProperties,
2644 mPointerGesture.currentGestureCoords,
2645 mPointerGesture.currentGestureIdToIndex,
2646 dispatchedGestureIdBits, id, 0, 0,
2647 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002648 }
2649 }
2650
2651 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002652 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002653 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2654 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2655 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2656 mPointerGesture.currentGestureProperties,
2657 mPointerGesture.currentGestureCoords,
2658 mPointerGesture.currentGestureIdToIndex,
2659 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2660 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002661 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2662 // Synthesize a hover move event after all pointers go up to indicate that
2663 // the pointer is hovering again even if the user is not currently touching
2664 // the touch pad. This ensures that a view will receive a fresh hover enter
2665 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002666 float x, y;
2667 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002668
2669 PointerProperties pointerProperties;
2670 pointerProperties.clear();
2671 pointerProperties.id = 0;
2672 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2673
2674 PointerCoords pointerCoords;
2675 pointerCoords.clear();
2676 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2677 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2678
2679 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002680 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2681 mSource, displayId, policyFlags,
2682 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2683 buttonState, MotionClassification::NONE,
2684 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2685 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2686 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002687 }
2688
2689 // Update state.
2690 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2691 if (!down) {
2692 mPointerGesture.lastGestureIdBits.clear();
2693 } else {
2694 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2695 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2696 uint32_t id = idBits.clearFirstMarkedBit();
2697 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2698 mPointerGesture.lastGestureProperties[index].copyFrom(
2699 mPointerGesture.currentGestureProperties[index]);
2700 mPointerGesture.lastGestureCoords[index].copyFrom(
2701 mPointerGesture.currentGestureCoords[index]);
2702 mPointerGesture.lastGestureIdToIndex[id] = index;
2703 }
2704 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002705 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002706}
2707
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002708std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2709 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002710 const MotionClassification classification =
2711 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2712 ? MotionClassification::TWO_FINGER_SWIPE
2713 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002714 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002715 // Cancel previously dispatches pointers.
2716 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2717 int32_t metaState = getContext()->getGlobalMetaState();
2718 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002719 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002720 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2721 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002722 mPointerGesture.lastGestureProperties,
2723 mPointerGesture.lastGestureCoords,
2724 mPointerGesture.lastGestureIdToIndex,
2725 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2726 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002727 }
2728
2729 // Reset the current pointer gesture.
2730 mPointerGesture.reset();
2731 mPointerVelocityControl.reset();
2732
2733 // Remove any current spots.
2734 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002735 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002736 mPointerController->clearSpots();
2737 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002738 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002739}
2740
2741bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2742 bool* outFinishPreviousGesture, bool isTimeout) {
2743 *outCancelPreviousGesture = false;
2744 *outFinishPreviousGesture = false;
2745
2746 // Handle TAP timeout.
2747 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002748 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002749
Michael Wright227c5542020-07-02 18:30:52 +01002750 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002751 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2752 // The tap/drag timeout has not yet expired.
2753 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2754 mConfig.pointerGestureTapDragInterval);
2755 } else {
2756 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002757 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002758 *outFinishPreviousGesture = true;
2759
2760 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002761 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002762 mPointerGesture.currentGestureIdBits.clear();
2763
2764 mPointerVelocityControl.reset();
2765 return true;
2766 }
2767 }
2768
2769 // We did not handle this timeout.
2770 return false;
2771 }
2772
2773 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2774 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2775
2776 // Update the velocity tracker.
2777 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002778 std::vector<float> positionsX;
2779 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002780 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002781 uint32_t id = idBits.clearFirstMarkedBit();
2782 const RawPointerData::Pointer& pointer =
2783 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002784 positionsX.push_back(pointer.x * mPointerXMovementScale);
2785 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002786 }
2787 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002788 {{AMOTION_EVENT_AXIS_X, positionsX},
2789 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002790 }
2791
2792 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2793 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002794 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2795 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2796 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 mPointerGesture.resetTap();
2798 }
2799
2800 // Pick a new active touch id if needed.
2801 // Choose an arbitrary pointer that just went down, if there is one.
2802 // Otherwise choose an arbitrary remaining pointer.
2803 // This guarantees we always have an active touch id when there is at least one pointer.
2804 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002805 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002807 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002808 mPointerGesture.firstTouchTime = when;
2809 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002810 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2811 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2812 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2813 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002814 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002815 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002816
2817 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002818 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002819 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002820 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2821 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2822 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002823 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824 *outFinishPreviousGesture = true;
2825 }
2826
2827 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002828 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002829 mPointerGesture.currentGestureIdBits.clear();
2830
2831 mPointerVelocityControl.reset();
2832 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2833 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2834 // The pointer follows the active touch point.
2835 // Emit DOWN, MOVE, UP events at the pointer location.
2836 //
2837 // Only the active touch matters; other fingers are ignored. This policy helps
2838 // to handle the case where the user places a second finger on the touch pad
2839 // to apply the necessary force to depress an integrated button below the surface.
2840 // We don't want the second finger to be delivered to applications.
2841 //
2842 // For this to work well, we need to make sure to track the pointer that is really
2843 // active. If the user first puts one finger down to click then adds another
2844 // finger to drag then the active pointer should switch to the finger that is
2845 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002846 ALOGD_IF(DEBUG_GESTURES,
2847 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2848 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002850 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002851 *outFinishPreviousGesture = true;
2852 mPointerGesture.activeGestureId = 0;
2853 }
2854
2855 // Switch pointers if needed.
2856 // Find the fastest pointer and follow it.
2857 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002858 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002860 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002861 ALOGD_IF(DEBUG_GESTURES,
2862 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2863 "bestSpeed=%0.3f",
2864 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 }
2866 }
2867
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002868 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869 // When using spots, the click will occur at the position of the anchor
2870 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002871 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 } else {
2873 mPointerVelocityControl.reset();
2874 }
2875
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002876 float x, y;
2877 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878
Michael Wright227c5542020-07-02 18:30:52 +01002879 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002880 mPointerGesture.currentGestureIdBits.clear();
2881 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2882 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2883 mPointerGesture.currentGestureProperties[0].clear();
2884 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2885 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2886 mPointerGesture.currentGestureCoords[0].clear();
2887 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2888 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2889 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2890 } else if (currentFingerCount == 0) {
2891 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002892 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002893 *outFinishPreviousGesture = true;
2894 }
2895
2896 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2897 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2898 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002899 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2900 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002901 lastFingerCount == 1) {
2902 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002903 float x, y;
2904 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002905 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2906 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002907 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002908
2909 mPointerGesture.tapUpTime = when;
2910 getContext()->requestTimeoutAtTime(when +
2911 mConfig.pointerGestureTapDragInterval);
2912
2913 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002914 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002915 mPointerGesture.currentGestureIdBits.clear();
2916 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2917 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2918 mPointerGesture.currentGestureProperties[0].clear();
2919 mPointerGesture.currentGestureProperties[0].id =
2920 mPointerGesture.activeGestureId;
2921 mPointerGesture.currentGestureProperties[0].toolType =
2922 AMOTION_EVENT_TOOL_TYPE_FINGER;
2923 mPointerGesture.currentGestureCoords[0].clear();
2924 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2925 mPointerGesture.tapX);
2926 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2927 mPointerGesture.tapY);
2928 mPointerGesture.currentGestureCoords[0]
2929 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2930
2931 tapped = true;
2932 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002933 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2934 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002935 }
2936 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002937 if (DEBUG_GESTURES) {
2938 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2939 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2940 (when - mPointerGesture.tapDownTime) * 0.000001f);
2941 } else {
2942 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2943 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 }
2946 }
2947
2948 mPointerVelocityControl.reset();
2949
2950 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002951 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002953 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 mPointerGesture.currentGestureIdBits.clear();
2955 }
2956 } else if (currentFingerCount == 1) {
2957 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2958 // The pointer follows the active touch point.
2959 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2960 // When in TAP_DRAG, emit MOVE events at the pointer location.
2961 ALOG_ASSERT(activeTouchId >= 0);
2962
Michael Wright227c5542020-07-02 18:30:52 +01002963 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2964 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002965 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002966 float x, y;
2967 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2969 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002970 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002971 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002972 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2973 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974 }
2975 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002976 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2977 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978 }
Michael Wright227c5542020-07-02 18:30:52 +01002979 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2980 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 }
2982
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002983 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002985 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 } else {
2987 mPointerVelocityControl.reset();
2988 }
2989
2990 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002991 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002992 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002993 down = true;
2994 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002995 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002996 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 *outFinishPreviousGesture = true;
2998 }
2999 mPointerGesture.activeGestureId = 0;
3000 down = false;
3001 }
3002
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003003 float x, y;
3004 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003005
3006 mPointerGesture.currentGestureIdBits.clear();
3007 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3008 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3009 mPointerGesture.currentGestureProperties[0].clear();
3010 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3011 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3012 mPointerGesture.currentGestureCoords[0].clear();
3013 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3014 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3015 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3016 down ? 1.0f : 0.0f);
3017
3018 if (lastFingerCount == 0 && currentFingerCount != 0) {
3019 mPointerGesture.resetTap();
3020 mPointerGesture.tapDownTime = when;
3021 mPointerGesture.tapX = x;
3022 mPointerGesture.tapY = y;
3023 }
3024 } else {
3025 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003026 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003027 }
3028
3029 mPointerController->setButtonState(mCurrentRawState.buttonState);
3030
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003031 if (DEBUG_GESTURES) {
3032 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3033 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3034 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3035 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3036 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3037 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3038 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3039 uint32_t id = idBits.clearFirstMarkedBit();
3040 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3041 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3042 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3043 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3044 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3045 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3046 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3047 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3048 }
3049 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3050 uint32_t id = idBits.clearFirstMarkedBit();
3051 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3052 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3053 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3054 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3055 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3056 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3057 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3058 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3059 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003060 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003061 return true;
3062}
3063
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003064bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3065 if (mPointerGesture.activeTouchId < 0) {
3066 mPointerGesture.resetQuietTime();
3067 return false;
3068 }
3069
3070 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3071 return true;
3072 }
3073
3074 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3075 bool isQuietTime = false;
3076 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3077 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3078 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3079 currentFingerCount < 2) {
3080 // Enter quiet time when exiting swipe or freeform state.
3081 // This is to prevent accidentally entering the hover state and flinging the
3082 // pointer when finishing a swipe and there is still one pointer left onscreen.
3083 isQuietTime = true;
3084 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3085 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3086 // Enter quiet time when releasing the button and there are still two or more
3087 // fingers down. This may indicate that one finger was used to press the button
3088 // but it has not gone up yet.
3089 isQuietTime = true;
3090 }
3091 if (isQuietTime) {
3092 mPointerGesture.quietTime = when;
3093 }
3094 return isQuietTime;
3095}
3096
3097std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3098 int32_t bestId = -1;
3099 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3100 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3101 uint32_t id = idBits.clearFirstMarkedBit();
3102 std::optional<float> vx =
3103 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3104 std::optional<float> vy =
3105 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3106 if (vx && vy) {
3107 float speed = hypotf(*vx, *vy);
3108 if (speed > bestSpeed) {
3109 bestId = id;
3110 bestSpeed = speed;
3111 }
3112 }
3113 }
3114 return std::make_pair(bestId, bestSpeed);
3115}
3116
3117void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3118 bool* finishPreviousGesture) {
3119 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3120 // to move before deciding what to do.
3121 //
3122 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3123 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3124 // just a press or long-press at the pointer location.
3125 //
3126 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3127 // pointer location.
3128 //
3129 // When the two fingers move enough or when additional fingers are added, we make a decision to
3130 // transition into SWIPE or FREEFORM mode accordingly.
3131 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3132 ALOG_ASSERT(activeTouchId >= 0);
3133
3134 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3135 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3136 bool settled =
3137 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3138 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3139 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3140 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3141 *finishPreviousGesture = true;
3142 } else if (!settled && currentFingerCount > lastFingerCount) {
3143 // Additional pointers have gone down but not yet settled.
3144 // Reset the gesture.
3145 ALOGD_IF(DEBUG_GESTURES,
3146 "Gestures: Resetting gesture since additional pointers went down for "
3147 "MULTITOUCH, settle time remaining %0.3fms",
3148 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3149 when) * 0.000001f);
3150 *cancelPreviousGesture = true;
3151 } else {
3152 // Continue previous gesture.
3153 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3154 }
3155
3156 if (*finishPreviousGesture || *cancelPreviousGesture) {
3157 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3158 mPointerGesture.activeGestureId = 0;
3159 mPointerGesture.referenceIdBits.clear();
3160 mPointerVelocityControl.reset();
3161
3162 // Use the centroid and pointer location as the reference points for the gesture.
3163 ALOGD_IF(DEBUG_GESTURES,
3164 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3165 "%0.3fms",
3166 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3167 when) * 0.000001f);
3168 mCurrentRawState.rawPointerData
3169 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3170 &mPointerGesture.referenceTouchY);
3171 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3172 &mPointerGesture.referenceGestureY);
3173 }
3174
3175 // Clear the reference deltas for fingers not yet included in the reference calculation.
3176 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3177 ~mPointerGesture.referenceIdBits.value);
3178 !idBits.isEmpty();) {
3179 uint32_t id = idBits.clearFirstMarkedBit();
3180 mPointerGesture.referenceDeltas[id].dx = 0;
3181 mPointerGesture.referenceDeltas[id].dy = 0;
3182 }
3183 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3184
3185 // Add delta for all fingers and calculate a common movement delta.
3186 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3187 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3188 mCurrentCookedState.fingerIdBits.value);
3189 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3190 bool first = (idBits == commonIdBits);
3191 uint32_t id = idBits.clearFirstMarkedBit();
3192 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3193 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3194 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3195 delta.dx += cpd.x - lpd.x;
3196 delta.dy += cpd.y - lpd.y;
3197
3198 if (first) {
3199 commonDeltaRawX = delta.dx;
3200 commonDeltaRawY = delta.dy;
3201 } else {
3202 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3203 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3204 }
3205 }
3206
3207 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3208 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3209 float dist[MAX_POINTER_ID + 1];
3210 int32_t distOverThreshold = 0;
3211 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3212 uint32_t id = idBits.clearFirstMarkedBit();
3213 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3214 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3215 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3216 distOverThreshold += 1;
3217 }
3218 }
3219
3220 // Only transition when at least two pointers have moved further than
3221 // the minimum distance threshold.
3222 if (distOverThreshold >= 2) {
3223 if (currentFingerCount > 2) {
3224 // There are more than two pointers, switch to FREEFORM.
3225 ALOGD_IF(DEBUG_GESTURES,
3226 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3227 currentFingerCount);
3228 *cancelPreviousGesture = true;
3229 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3230 } else {
3231 // There are exactly two pointers.
3232 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3233 uint32_t id1 = idBits.clearFirstMarkedBit();
3234 uint32_t id2 = idBits.firstMarkedBit();
3235 const RawPointerData::Pointer& p1 =
3236 mCurrentRawState.rawPointerData.pointerForId(id1);
3237 const RawPointerData::Pointer& p2 =
3238 mCurrentRawState.rawPointerData.pointerForId(id2);
3239 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3240 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3241 // There are two pointers but they are too far apart for a SWIPE,
3242 // switch to FREEFORM.
3243 ALOGD_IF(DEBUG_GESTURES,
3244 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3245 mutualDistance, mPointerGestureMaxSwipeWidth);
3246 *cancelPreviousGesture = true;
3247 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3248 } else {
3249 // There are two pointers. Wait for both pointers to start moving
3250 // before deciding whether this is a SWIPE or FREEFORM gesture.
3251 float dist1 = dist[id1];
3252 float dist2 = dist[id2];
3253 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3254 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3255 // Calculate the dot product of the displacement vectors.
3256 // When the vectors are oriented in approximately the same direction,
3257 // the angle betweeen them is near zero and the cosine of the angle
3258 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3259 // mag(v2).
3260 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3261 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3262 float dx1 = delta1.dx * mPointerXZoomScale;
3263 float dy1 = delta1.dy * mPointerYZoomScale;
3264 float dx2 = delta2.dx * mPointerXZoomScale;
3265 float dy2 = delta2.dy * mPointerYZoomScale;
3266 float dot = dx1 * dx2 + dy1 * dy2;
3267 float cosine = dot / (dist1 * dist2); // denominator always > 0
3268 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3269 // Pointers are moving in the same direction. Switch to SWIPE.
3270 ALOGD_IF(DEBUG_GESTURES,
3271 "Gestures: PRESS transitioned to SWIPE, "
3272 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3273 "cosine %0.3f >= %0.3f",
3274 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3275 mConfig.pointerGestureMultitouchMinDistance, cosine,
3276 mConfig.pointerGestureSwipeTransitionAngleCosine);
3277 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3278 } else {
3279 // Pointers are moving in different directions. Switch to FREEFORM.
3280 ALOGD_IF(DEBUG_GESTURES,
3281 "Gestures: PRESS transitioned to FREEFORM, "
3282 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3283 "cosine %0.3f < %0.3f",
3284 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3285 mConfig.pointerGestureMultitouchMinDistance, cosine,
3286 mConfig.pointerGestureSwipeTransitionAngleCosine);
3287 *cancelPreviousGesture = true;
3288 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3289 }
3290 }
3291 }
3292 }
3293 }
3294 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3295 // Switch from SWIPE to FREEFORM if additional pointers go down.
3296 // Cancel previous gesture.
3297 if (currentFingerCount > 2) {
3298 ALOGD_IF(DEBUG_GESTURES,
3299 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3300 currentFingerCount);
3301 *cancelPreviousGesture = true;
3302 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3303 }
3304 }
3305
3306 // Move the reference points based on the overall group motion of the fingers
3307 // except in PRESS mode while waiting for a transition to occur.
3308 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3309 (commonDeltaRawX || commonDeltaRawY)) {
3310 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3311 uint32_t id = idBits.clearFirstMarkedBit();
3312 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3313 delta.dx = 0;
3314 delta.dy = 0;
3315 }
3316
3317 mPointerGesture.referenceTouchX += commonDeltaRawX;
3318 mPointerGesture.referenceTouchY += commonDeltaRawY;
3319
3320 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3321 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3322
3323 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3324 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3325
3326 mPointerGesture.referenceGestureX += commonDeltaX;
3327 mPointerGesture.referenceGestureY += commonDeltaY;
3328 }
3329
3330 // Report gestures.
3331 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3332 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3333 // PRESS or SWIPE mode.
3334 ALOGD_IF(DEBUG_GESTURES,
3335 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3336 "currentTouchPointerCount=%d",
3337 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3338 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3339
3340 mPointerGesture.currentGestureIdBits.clear();
3341 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3342 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3343 mPointerGesture.currentGestureProperties[0].clear();
3344 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3345 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3346 mPointerGesture.currentGestureCoords[0].clear();
3347 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3348 mPointerGesture.referenceGestureX);
3349 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3350 mPointerGesture.referenceGestureY);
3351 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3352 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3353 float xOffset = static_cast<float>(commonDeltaRawX) /
3354 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3355 float yOffset = static_cast<float>(commonDeltaRawY) /
3356 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3357 mPointerGesture.currentGestureCoords[0]
3358 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3359 mPointerGesture.currentGestureCoords[0]
3360 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3361 }
3362 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3363 // FREEFORM mode.
3364 ALOGD_IF(DEBUG_GESTURES,
3365 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3366 "currentTouchPointerCount=%d",
3367 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3368 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3369
3370 mPointerGesture.currentGestureIdBits.clear();
3371
3372 BitSet32 mappedTouchIdBits;
3373 BitSet32 usedGestureIdBits;
3374 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3375 // Initially, assign the active gesture id to the active touch point
3376 // if there is one. No other touch id bits are mapped yet.
3377 if (!*cancelPreviousGesture) {
3378 mappedTouchIdBits.markBit(activeTouchId);
3379 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3380 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3381 mPointerGesture.activeGestureId;
3382 } else {
3383 mPointerGesture.activeGestureId = -1;
3384 }
3385 } else {
3386 // Otherwise, assume we mapped all touches from the previous frame.
3387 // Reuse all mappings that are still applicable.
3388 mappedTouchIdBits.value =
3389 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3390 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3391
3392 // Check whether we need to choose a new active gesture id because the
3393 // current went went up.
3394 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3395 ~mCurrentCookedState.fingerIdBits.value);
3396 !upTouchIdBits.isEmpty();) {
3397 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3398 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3399 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3400 mPointerGesture.activeGestureId = -1;
3401 break;
3402 }
3403 }
3404 }
3405
3406 ALOGD_IF(DEBUG_GESTURES,
3407 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3408 "activeGestureId=%d",
3409 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3410
3411 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3412 for (uint32_t i = 0; i < currentFingerCount; i++) {
3413 uint32_t touchId = idBits.clearFirstMarkedBit();
3414 uint32_t gestureId;
3415 if (!mappedTouchIdBits.hasBit(touchId)) {
3416 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3417 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3418 ALOGD_IF(DEBUG_GESTURES,
3419 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3420 gestureId);
3421 } else {
3422 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3423 ALOGD_IF(DEBUG_GESTURES,
3424 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3425 touchId, gestureId);
3426 }
3427 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3428 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3429
3430 const RawPointerData::Pointer& pointer =
3431 mCurrentRawState.rawPointerData.pointerForId(touchId);
3432 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3433 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3434 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3435
3436 mPointerGesture.currentGestureProperties[i].clear();
3437 mPointerGesture.currentGestureProperties[i].id = gestureId;
3438 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3439 mPointerGesture.currentGestureCoords[i].clear();
3440 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3441 mPointerGesture.referenceGestureX +
3442 deltaX);
3443 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3444 mPointerGesture.referenceGestureY +
3445 deltaY);
3446 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3447 }
3448
3449 if (mPointerGesture.activeGestureId < 0) {
3450 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3451 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3452 mPointerGesture.activeGestureId);
3453 }
3454 }
3455}
3456
Harry Cutts714d1ad2022-08-24 16:36:43 +00003457void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3458 const RawPointerData::Pointer& currentPointer =
3459 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3460 const RawPointerData::Pointer& lastPointer =
3461 mLastRawState.rawPointerData.pointerForId(pointerId);
3462 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3463 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3464
3465 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3466 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3467
3468 mPointerController->move(deltaX, deltaY);
3469}
3470
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003471std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3472 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003473 mPointerSimple.currentCoords.clear();
3474 mPointerSimple.currentProperties.clear();
3475
3476 bool down, hovering;
3477 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3478 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3479 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003480 mPointerController
3481 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3482 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003483
3484 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3485 down = !hovering;
3486
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003487 float x, y;
3488 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489 mPointerSimple.currentCoords.copyFrom(
3490 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3491 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3492 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3493 mPointerSimple.currentProperties.id = 0;
3494 mPointerSimple.currentProperties.toolType =
3495 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3496 } else {
3497 down = false;
3498 hovering = false;
3499 }
3500
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003501 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003502}
3503
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003504std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3505 uint32_t policyFlags) {
3506 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003507}
3508
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003509std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3510 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003511 mPointerSimple.currentCoords.clear();
3512 mPointerSimple.currentProperties.clear();
3513
3514 bool down, hovering;
3515 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3516 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003518 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003519 } else {
3520 mPointerVelocityControl.reset();
3521 }
3522
3523 down = isPointerDown(mCurrentRawState.buttonState);
3524 hovering = !down;
3525
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003526 float x, y;
3527 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003528 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003529 mPointerSimple.currentCoords.copyFrom(
3530 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3531 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3532 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3533 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3534 hovering ? 0.0f : 1.0f);
3535 mPointerSimple.currentProperties.id = 0;
3536 mPointerSimple.currentProperties.toolType =
3537 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3538 } else {
3539 mPointerVelocityControl.reset();
3540
3541 down = false;
3542 hovering = false;
3543 }
3544
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003545 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546}
3547
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003548std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3549 uint32_t policyFlags) {
3550 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003551
3552 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003553
3554 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003555}
3556
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003557std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3558 uint32_t policyFlags, bool down,
3559 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003560 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3561 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003562 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003564
3565 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003566 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567 mPointerController->clearSpots();
3568 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003569 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003571 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572 }
Garfield Tan9514d782020-11-10 16:37:23 -08003573 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003574
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003575 float xCursorPosition, yCursorPosition;
3576 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003577
3578 if (mPointerSimple.down && !down) {
3579 mPointerSimple.down = false;
3580
3581 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003582 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3583 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3584 0, metaState, mLastRawState.buttonState,
3585 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3586 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3587 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3588 yCursorPosition, mPointerSimple.downTime,
3589 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590 }
3591
3592 if (mPointerSimple.hovering && !hovering) {
3593 mPointerSimple.hovering = false;
3594
3595 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003596 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3597 mSource, displayId, policyFlags,
3598 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3599 mLastRawState.buttonState, MotionClassification::NONE,
3600 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3601 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3602 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3603 yCursorPosition, mPointerSimple.downTime,
3604 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003605 }
3606
3607 if (down) {
3608 if (!mPointerSimple.down) {
3609 mPointerSimple.down = true;
3610 mPointerSimple.downTime = when;
3611
3612 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003613 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3614 mSource, displayId, policyFlags,
3615 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3616 mCurrentRawState.buttonState, MotionClassification::NONE,
3617 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3618 &mPointerSimple.currentProperties,
3619 &mPointerSimple.currentCoords, mOrientedXPrecision,
3620 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3621 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003622 }
3623
3624 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003625 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3626 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3627 0, 0, metaState, mCurrentRawState.buttonState,
3628 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3629 &mPointerSimple.currentProperties,
3630 &mPointerSimple.currentCoords, mOrientedXPrecision,
3631 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3632 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003633 }
3634
3635 if (hovering) {
3636 if (!mPointerSimple.hovering) {
3637 mPointerSimple.hovering = true;
3638
3639 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003640 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3641 mSource, displayId, policyFlags,
3642 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3643 mCurrentRawState.buttonState, MotionClassification::NONE,
3644 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3645 &mPointerSimple.currentProperties,
3646 &mPointerSimple.currentCoords, mOrientedXPrecision,
3647 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3648 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003649 }
3650
3651 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003652 out.push_back(
3653 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3654 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3655 metaState, mCurrentRawState.buttonState,
3656 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3657 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3658 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3659 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003660 }
3661
3662 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3663 float vscroll = mCurrentRawState.rawVScroll;
3664 float hscroll = mCurrentRawState.rawHScroll;
3665 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3666 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3667
3668 // Send scroll.
3669 PointerCoords pointerCoords;
3670 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3671 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3672 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3673
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003674 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3675 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3676 0, 0, metaState, mCurrentRawState.buttonState,
3677 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3678 &mPointerSimple.currentProperties, &pointerCoords,
3679 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3680 yCursorPosition, mPointerSimple.downTime,
3681 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003682 }
3683
3684 // Save state.
3685 if (down || hovering) {
3686 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3687 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003688 mPointerSimple.displayId = displayId;
3689 mPointerSimple.source = mSource;
3690 mPointerSimple.lastCursorX = xCursorPosition;
3691 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003692 } else {
3693 mPointerSimple.reset();
3694 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003695 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696}
3697
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003698std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3699 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003700 std::list<NotifyArgs> out;
3701 if (mPointerSimple.down || mPointerSimple.hovering) {
3702 int32_t metaState = getContext()->getGlobalMetaState();
3703 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3704 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3705 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3706 metaState, mLastRawState.buttonState,
3707 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3708 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3709 mOrientedXPrecision, mOrientedYPrecision,
3710 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3711 mPointerSimple.downTime,
3712 /* videoFrames */ {}));
3713 if (mPointerController != nullptr) {
3714 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3715 }
3716 }
3717 mPointerSimple.reset();
3718 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003719}
3720
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003721NotifyMotionArgs TouchInputMapper::dispatchMotion(
3722 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3723 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003724 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3725 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003726 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003727 PointerCoords pointerCoords[MAX_POINTERS];
3728 PointerProperties pointerProperties[MAX_POINTERS];
3729 uint32_t pointerCount = 0;
3730 while (!idBits.isEmpty()) {
3731 uint32_t id = idBits.clearFirstMarkedBit();
3732 uint32_t index = idToIndex[id];
3733 pointerProperties[pointerCount].copyFrom(properties[index]);
3734 pointerCoords[pointerCount].copyFrom(coords[index]);
3735
3736 if (changedId >= 0 && id == uint32_t(changedId)) {
3737 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3738 }
3739
3740 pointerCount += 1;
3741 }
3742
3743 ALOG_ASSERT(pointerCount != 0);
3744
3745 if (changedId >= 0 && pointerCount == 1) {
3746 // Replace initial down and final up action.
3747 // We can compare the action without masking off the changed pointer index
3748 // because we know the index is 0.
3749 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3750 action = AMOTION_EVENT_ACTION_DOWN;
3751 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003752 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3753 action = AMOTION_EVENT_ACTION_CANCEL;
3754 } else {
3755 action = AMOTION_EVENT_ACTION_UP;
3756 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003757 } else {
3758 // Can't happen.
3759 ALOG_ASSERT(false);
3760 }
3761 }
3762 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3763 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003764 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003765 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003766 }
3767 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3768 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003769 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003770 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003771 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003772 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3773 policyFlags, action, actionButton, flags, metaState, buttonState,
3774 classification, edgeFlags, pointerCount, pointerProperties,
3775 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3776 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003777}
3778
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003779std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3780 std::list<NotifyArgs> out;
3781 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3782 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3783 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003784}
3785
Prabir Pradhan1728b212021-10-19 16:00:03 -07003786// Transform input device coordinates to display panel coordinates.
3787void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003788 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3789 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3790
arthurhunga36b28e2020-12-29 20:28:15 +08003791 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3792 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3793
Prabir Pradhan1728b212021-10-19 16:00:03 -07003794 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003795 // 0 - no swap and reverse.
3796 // 90 - swap x/y and reverse y.
3797 // 180 - reverse x, y.
3798 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003799 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003800 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003801 x = xScaled;
3802 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003803 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003804 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003805 y = xScaledMax;
3806 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003807 break;
3808 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003809 x = xScaledMax;
3810 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003811 break;
3812 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003813 y = xScaled;
3814 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003815 break;
3816 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003817 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003818 }
3819}
3820
Prabir Pradhan1728b212021-10-19 16:00:03 -07003821bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003822 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3823 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3824
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003825 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003826 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003827 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003828 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003829}
3830
3831const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3832 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003833 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3834 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3835 "left=%d, top=%d, right=%d, bottom=%d",
3836 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3837 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003838
3839 if (virtualKey.isHit(x, y)) {
3840 return &virtualKey;
3841 }
3842 }
3843
3844 return nullptr;
3845}
3846
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003847void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3848 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3849 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003850
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003851 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003852
3853 if (currentPointerCount == 0) {
3854 // No pointers to assign.
3855 return;
3856 }
3857
3858 if (lastPointerCount == 0) {
3859 // All pointers are new.
3860 for (uint32_t i = 0; i < currentPointerCount; i++) {
3861 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003862 current.rawPointerData.pointers[i].id = id;
3863 current.rawPointerData.idToIndex[id] = i;
3864 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003865 }
3866 return;
3867 }
3868
3869 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003870 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003871 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003872 uint32_t id = last.rawPointerData.pointers[0].id;
3873 current.rawPointerData.pointers[0].id = id;
3874 current.rawPointerData.idToIndex[id] = 0;
3875 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003876 return;
3877 }
3878
3879 // General case.
3880 // We build a heap of squared euclidean distances between current and last pointers
3881 // associated with the current and last pointer indices. Then, we find the best
3882 // match (by distance) for each current pointer.
3883 // The pointers must have the same tool type but it is possible for them to
3884 // transition from hovering to touching or vice-versa while retaining the same id.
3885 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3886
3887 uint32_t heapSize = 0;
3888 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3889 currentPointerIndex++) {
3890 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3891 lastPointerIndex++) {
3892 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003893 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003894 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003895 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003896 if (currentPointer.toolType == lastPointer.toolType) {
3897 int64_t deltaX = currentPointer.x - lastPointer.x;
3898 int64_t deltaY = currentPointer.y - lastPointer.y;
3899
3900 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3901
3902 // Insert new element into the heap (sift up).
3903 heap[heapSize].currentPointerIndex = currentPointerIndex;
3904 heap[heapSize].lastPointerIndex = lastPointerIndex;
3905 heap[heapSize].distance = distance;
3906 heapSize += 1;
3907 }
3908 }
3909 }
3910
3911 // Heapify
3912 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3913 startIndex -= 1;
3914 for (uint32_t parentIndex = startIndex;;) {
3915 uint32_t childIndex = parentIndex * 2 + 1;
3916 if (childIndex >= heapSize) {
3917 break;
3918 }
3919
3920 if (childIndex + 1 < heapSize &&
3921 heap[childIndex + 1].distance < heap[childIndex].distance) {
3922 childIndex += 1;
3923 }
3924
3925 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3926 break;
3927 }
3928
3929 swap(heap[parentIndex], heap[childIndex]);
3930 parentIndex = childIndex;
3931 }
3932 }
3933
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003934 if (DEBUG_POINTER_ASSIGNMENT) {
3935 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3936 for (size_t i = 0; i < heapSize; i++) {
3937 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3938 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3939 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003940 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003941
3942 // Pull matches out by increasing order of distance.
3943 // To avoid reassigning pointers that have already been matched, the loop keeps track
3944 // of which last and current pointers have been matched using the matchedXXXBits variables.
3945 // It also tracks the used pointer id bits.
3946 BitSet32 matchedLastBits(0);
3947 BitSet32 matchedCurrentBits(0);
3948 BitSet32 usedIdBits(0);
3949 bool first = true;
3950 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3951 while (heapSize > 0) {
3952 if (first) {
3953 // The first time through the loop, we just consume the root element of
3954 // the heap (the one with smallest distance).
3955 first = false;
3956 } else {
3957 // Previous iterations consumed the root element of the heap.
3958 // Pop root element off of the heap (sift down).
3959 heap[0] = heap[heapSize];
3960 for (uint32_t parentIndex = 0;;) {
3961 uint32_t childIndex = parentIndex * 2 + 1;
3962 if (childIndex >= heapSize) {
3963 break;
3964 }
3965
3966 if (childIndex + 1 < heapSize &&
3967 heap[childIndex + 1].distance < heap[childIndex].distance) {
3968 childIndex += 1;
3969 }
3970
3971 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3972 break;
3973 }
3974
3975 swap(heap[parentIndex], heap[childIndex]);
3976 parentIndex = childIndex;
3977 }
3978
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003979 if (DEBUG_POINTER_ASSIGNMENT) {
3980 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3981 for (size_t j = 0; j < heapSize; j++) {
3982 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3983 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3984 heap[j].distance);
3985 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003986 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003987 }
3988
3989 heapSize -= 1;
3990
3991 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3992 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3993
3994 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3995 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3996
3997 matchedCurrentBits.markBit(currentPointerIndex);
3998 matchedLastBits.markBit(lastPointerIndex);
3999
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004000 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4001 current.rawPointerData.pointers[currentPointerIndex].id = id;
4002 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4003 current.rawPointerData.markIdBit(id,
4004 current.rawPointerData.isHovering(
4005 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004006 usedIdBits.markBit(id);
4007
Harry Cutts45483602022-08-24 14:36:48 +00004008 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4009 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4010 ", distance=%" PRIu64,
4011 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004012 break;
4013 }
4014 }
4015
4016 // Assign fresh ids to pointers that were not matched in the process.
4017 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4018 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4019 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4020
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004021 current.rawPointerData.pointers[currentPointerIndex].id = id;
4022 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4023 current.rawPointerData.markIdBit(id,
4024 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004025
Harry Cutts45483602022-08-24 14:36:48 +00004026 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4027 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4028 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004029 }
4030}
4031
4032int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4033 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4034 return AKEY_STATE_VIRTUAL;
4035 }
4036
4037 for (const VirtualKey& virtualKey : mVirtualKeys) {
4038 if (virtualKey.keyCode == keyCode) {
4039 return AKEY_STATE_UP;
4040 }
4041 }
4042
4043 return AKEY_STATE_UNKNOWN;
4044}
4045
4046int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4047 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4048 return AKEY_STATE_VIRTUAL;
4049 }
4050
4051 for (const VirtualKey& virtualKey : mVirtualKeys) {
4052 if (virtualKey.scanCode == scanCode) {
4053 return AKEY_STATE_UP;
4054 }
4055 }
4056
4057 return AKEY_STATE_UNKNOWN;
4058}
4059
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004060bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4061 const std::vector<int32_t>& keyCodes,
4062 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004063 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004064 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004065 if (virtualKey.keyCode == keyCodes[i]) {
4066 outFlags[i] = 1;
4067 }
4068 }
4069 }
4070
4071 return true;
4072}
4073
4074std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4075 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004076 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004077 return std::make_optional(mPointerController->getDisplayId());
4078 } else {
4079 return std::make_optional(mViewport.displayId);
4080 }
4081 }
4082 return std::nullopt;
4083}
4084
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004085} // namespace android