blob: 5e81ff87e8a800489f48e87b6965d1dbd0c45d28 [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);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000257 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
258 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700259 dump += INDENT3 "External Stylus State:\n";
260 dumpStylusState(dump, mExternalStylusState);
261
Michael Wright227c5542020-07-02 18:30:52 +0100262 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700263 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
264 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
265 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
266 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
267 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
268 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
269 }
270}
271
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700272std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
273 const InputReaderConfiguration* config,
274 uint32_t changes) {
275 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700276
277 mConfig = *config;
278
279 if (!changes) { // first time only
280 // Configure basic parameters.
281 configureParameters();
282
283 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800284 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000285 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700286
287 // Configure absolute axis information.
288 configureRawPointerAxes();
289
290 // Prepare input device calibration.
291 parseCalibration();
292 resolveCalibration();
293 }
294
295 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
296 // Update location calibration to reflect current settings
297 updateAffineTransformation();
298 }
299
300 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
301 // Update pointer speed.
302 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
303 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
304 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
305 }
306
307 bool resetNeeded = false;
308 if (!changes ||
309 (changes &
310 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800311 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700312 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
313 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
314 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700315 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700316 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700317 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700318 }
319
320 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700321 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000322
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700323 // Send reset, unless this is the first time the device has been configured,
324 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000325 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700326 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700327 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700328}
329
330void TouchInputMapper::resolveExternalStylusPresence() {
331 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800332 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333 mExternalStylusConnected = !devices.empty();
334
335 if (!mExternalStylusConnected) {
336 resetExternalStylus();
337 }
338}
339
340void TouchInputMapper::configureParameters() {
341 // Use the pointer presentation mode for devices that do not support distinct
342 // multitouch. The spot-based presentation relies on being able to accurately
343 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800344 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100345 ? Parameters::GestureMode::SINGLE_TOUCH
346 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700347
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700348 std::string gestureModeString;
349 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800350 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100352 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700353 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100354 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700356 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700357 }
358 }
359
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800360 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700361 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100362 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800363 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100365 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700366 } else {
367 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100368 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700369 }
370
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800371 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700372
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700373 std::string deviceTypeString;
374 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800375 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700376 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100377 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700378 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100379 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700380 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100381 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700382 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700383 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384 }
385 }
386
Michael Wright227c5542020-07-02 18:30:52 +0100387 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700388 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800389 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700391 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700392 std::string orientationString;
393 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700394 orientationString)) {
395 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
396 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
397 } else if (orientationString == "ORIENTATION_90") {
398 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
399 } else if (orientationString == "ORIENTATION_180") {
400 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
401 } else if (orientationString == "ORIENTATION_270") {
402 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
403 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700404 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700405 }
406 }
407
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700408 mParameters.hasAssociatedDisplay = false;
409 mParameters.associatedDisplayIsExternal = false;
410 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100411 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
412 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700413 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100414 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800415 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700416 std::string uniqueDisplayId;
417 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700419 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
420 }
421 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800422 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423 mParameters.hasAssociatedDisplay = true;
424 }
425
426 // Initial downs on external touch devices should wake the device.
427 // Normally we don't do this for internal touch screens to prevent them from waking
428 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800429 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700430 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000431
432 mParameters.supportsUsi = false;
433 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
434 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700435
436 mParameters.enableForInactiveViewport = false;
437 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
438 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439}
440
441void TouchInputMapper::dumpParameters(std::string& dump) {
442 dump += INDENT3 "Parameters:\n";
443
Dominik Laskowski75788452021-02-09 18:51:25 -0800444 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700445
Dominik Laskowski75788452021-02-09 18:51:25 -0800446 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447
448 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
449 "displayId='%s'\n",
450 toString(mParameters.hasAssociatedDisplay),
451 toString(mParameters.associatedDisplayIsExternal),
452 mParameters.uniqueDisplayId.c_str());
453 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800454 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000455 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700456 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
457 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458}
459
460void TouchInputMapper::configureRawPointerAxes() {
461 mRawPointerAxes.clear();
462}
463
464void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
465 dump += INDENT3 "Raw Touch Axes:\n";
466 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
467 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
468 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
469 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
470 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
471 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
472 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
473 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
474 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
475 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
476 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
477 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
478 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
479}
480
481bool TouchInputMapper::hasExternalStylus() const {
482 return mExternalStylusConnected;
483}
484
485/**
486 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000487 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800488 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000489 * 3. Get the matching viewport by either unique id in idc file or by the display type
490 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800491 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700492 */
493std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800494 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000495 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800496 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700497 }
498
Christine Franks2a2293c2022-01-18 11:51:16 -0800499 const std::optional<std::string> associatedDisplayUniqueId =
500 getDeviceContext().getAssociatedDisplayUniqueId();
501 if (associatedDisplayUniqueId) {
502 return getDeviceContext().getAssociatedViewport();
503 }
504
Michael Wright227c5542020-07-02 18:30:52 +0100505 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800506 std::optional<DisplayViewport> viewport =
507 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
508 if (viewport) {
509 return viewport;
510 } else {
511 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
512 mConfig.defaultPointerDisplayId);
513 }
514 }
515
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700516 // Check if uniqueDisplayId is specified in idc file.
517 if (!mParameters.uniqueDisplayId.empty()) {
518 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
519 }
520
521 ViewportType viewportTypeToUse;
522 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100523 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700524 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100525 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700526 }
527
528 std::optional<DisplayViewport> viewport =
529 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100530 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700531 ALOGW("Input device %s should be associated with external display, "
532 "fallback to internal one for the external viewport is not found.",
533 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100534 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700535 }
536
537 return viewport;
538 }
539
540 // No associated display, return a non-display viewport.
541 DisplayViewport newViewport;
542 // Raw width and height in the natural orientation.
543 int32_t rawWidth = mRawPointerAxes.getRawWidth();
544 int32_t rawHeight = mRawPointerAxes.getRawHeight();
545 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
546 return std::make_optional(newViewport);
547}
548
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800549int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
550 if (resolution < 0) {
551 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
552 getDeviceName().c_str());
553 return 0;
554 }
555 return resolution;
556}
557
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800558void TouchInputMapper::initializeSizeRanges() {
559 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
560 mSizeScale = 0.0f;
561 return;
562 }
563
564 // Size of diagonal axis.
565 const float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
566
567 // Size factors.
568 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
569 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
570 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
571 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
572 } else {
573 mSizeScale = 0.0f;
574 }
575
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700576 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
577 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
578 .source = mSource,
579 .min = 0,
580 .max = diagonalSize,
581 .flat = 0,
582 .fuzz = 0,
583 .resolution = 0,
584 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800585
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800586 if (mRawPointerAxes.touchMajor.valid) {
587 mRawPointerAxes.touchMajor.resolution =
588 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700589 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800590 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800591
592 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700593 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800594 if (mRawPointerAxes.touchMinor.valid) {
595 mRawPointerAxes.touchMinor.resolution =
596 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700597 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800598 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800599
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700600 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
601 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
602 .source = mSource,
603 .min = 0,
604 .max = diagonalSize,
605 .flat = 0,
606 .fuzz = 0,
607 .resolution = 0,
608 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800609 if (mRawPointerAxes.toolMajor.valid) {
610 mRawPointerAxes.toolMajor.resolution =
611 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700612 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800613 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800614
615 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700616 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800617 if (mRawPointerAxes.toolMinor.valid) {
618 mRawPointerAxes.toolMinor.resolution =
619 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700620 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800621 }
622
623 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700624 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
625 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
626 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
627 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800628 } else {
629 // Support for other calibrations can be added here.
630 ALOGW("%s calibration is not supported for size ranges at the moment. "
631 "Using raw resolution instead",
632 ftl::enum_string(mCalibration.sizeCalibration).c_str());
633 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800634
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700635 mOrientedRanges.size = InputDeviceInfo::MotionRange{
636 .axis = AMOTION_EVENT_AXIS_SIZE,
637 .source = mSource,
638 .min = 0,
639 .max = 1.0,
640 .flat = 0,
641 .fuzz = 0,
642 .resolution = 0,
643 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800644}
645
646void TouchInputMapper::initializeOrientedRanges() {
647 // Configure X and Y factors.
648 mXScale = float(mDisplayWidth) / mRawPointerAxes.getRawWidth();
649 mYScale = float(mDisplayHeight) / mRawPointerAxes.getRawHeight();
650 mXPrecision = 1.0f / mXScale;
651 mYPrecision = 1.0f / mYScale;
652
653 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
654 mOrientedRanges.x.source = mSource;
655 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
656 mOrientedRanges.y.source = mSource;
657
658 // Scale factor for terms that are not oriented in a particular axis.
659 // If the pixels are square then xScale == yScale otherwise we fake it
660 // by choosing an average.
661 mGeometricScale = avg(mXScale, mYScale);
662
663 initializeSizeRanges();
664
665 // Pressure factors.
666 mPressureScale = 0;
667 float pressureMax = 1.0;
668 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
669 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700670 if (mCalibration.pressureScale) {
671 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800672 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
673 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
674 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
675 }
676 }
677
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700678 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
679 .axis = AMOTION_EVENT_AXIS_PRESSURE,
680 .source = mSource,
681 .min = 0,
682 .max = pressureMax,
683 .flat = 0,
684 .fuzz = 0,
685 .resolution = 0,
686 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800687
688 // Tilt
689 mTiltXCenter = 0;
690 mTiltXScale = 0;
691 mTiltYCenter = 0;
692 mTiltYScale = 0;
693 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
694 if (mHaveTilt) {
695 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
696 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
697 mTiltXScale = M_PI / 180;
698 mTiltYScale = M_PI / 180;
699
700 if (mRawPointerAxes.tiltX.resolution) {
701 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
702 }
703 if (mRawPointerAxes.tiltY.resolution) {
704 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
705 }
706
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700707 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
708 .axis = AMOTION_EVENT_AXIS_TILT,
709 .source = mSource,
710 .min = 0,
711 .max = M_PI_2,
712 .flat = 0,
713 .fuzz = 0,
714 .resolution = 0,
715 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800716 }
717
718 // Orientation
719 mOrientationScale = 0;
720 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700721 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
722 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
723 .source = mSource,
724 .min = -M_PI,
725 .max = M_PI,
726 .flat = 0,
727 .fuzz = 0,
728 .resolution = 0,
729 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800730
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800731 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
732 if (mCalibration.orientationCalibration ==
733 Calibration::OrientationCalibration::INTERPOLATED) {
734 if (mRawPointerAxes.orientation.valid) {
735 if (mRawPointerAxes.orientation.maxValue > 0) {
736 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
737 } else if (mRawPointerAxes.orientation.minValue < 0) {
738 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
739 } else {
740 mOrientationScale = 0;
741 }
742 }
743 }
744
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700745 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
746 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
747 .source = mSource,
748 .min = -M_PI_2,
749 .max = M_PI_2,
750 .flat = 0,
751 .fuzz = 0,
752 .resolution = 0,
753 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800754 }
755
756 // Distance
757 mDistanceScale = 0;
758 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
759 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700760 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800761 }
762
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700763 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800764
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700765 .axis = AMOTION_EVENT_AXIS_DISTANCE,
766 .source = mSource,
767 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
768 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
769 .flat = 0,
770 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
771 .resolution = 0,
772 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800773 }
774
775 // Compute oriented precision, scales and ranges.
776 // Note that the maximum value reported is an inclusive maximum value so it is one
777 // unit less than the total width or height of the display.
778 switch (mInputDeviceOrientation) {
779 case DISPLAY_ORIENTATION_90:
780 case DISPLAY_ORIENTATION_270:
781 mOrientedXPrecision = mYPrecision;
782 mOrientedYPrecision = mXPrecision;
783
784 mOrientedRanges.x.min = 0;
785 mOrientedRanges.x.max = mDisplayHeight - 1;
786 mOrientedRanges.x.flat = 0;
787 mOrientedRanges.x.fuzz = 0;
788 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
789
790 mOrientedRanges.y.min = 0;
791 mOrientedRanges.y.max = mDisplayWidth - 1;
792 mOrientedRanges.y.flat = 0;
793 mOrientedRanges.y.fuzz = 0;
794 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
795 break;
796
797 default:
798 mOrientedXPrecision = mXPrecision;
799 mOrientedYPrecision = mYPrecision;
800
801 mOrientedRanges.x.min = 0;
802 mOrientedRanges.x.max = mDisplayWidth - 1;
803 mOrientedRanges.x.flat = 0;
804 mOrientedRanges.x.fuzz = 0;
805 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
806
807 mOrientedRanges.y.min = 0;
808 mOrientedRanges.y.max = mDisplayHeight - 1;
809 mOrientedRanges.y.flat = 0;
810 mOrientedRanges.y.fuzz = 0;
811 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
812 break;
813 }
814}
815
Prabir Pradhan1728b212021-10-19 16:00:03 -0700816void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000817 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700818
819 resolveExternalStylusPresence();
820
821 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100822 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000823 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700824 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100825 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700826 if (hasStylus()) {
827 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000828 } else {
829 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700830 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800831 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700832 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100833 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700834 if (hasStylus()) {
835 mSource |= AINPUT_SOURCE_STYLUS;
836 }
837 if (hasExternalStylus()) {
838 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
839 }
Michael Wright227c5542020-07-02 18:30:52 +0100840 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700841 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100842 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700843 } else {
844 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100845 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700846 }
847
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000848 const std::optional<DisplayViewport> newViewportOpt = findViewport();
849
850 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700851 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
852 ALOGW("Touch device '%s' did not report support for X or Y axis! "
853 "The device will be inoperable.",
854 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100855 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000856 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700857 ALOGI("Touch device '%s' could not query the properties of its associated "
858 "display. The device will be inoperable until the display size "
859 "becomes available.",
860 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100861 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700862 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000863 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
864 getDeviceName().c_str(), getDeviceId());
865 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000866 }
867
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700868 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700869 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
870 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
HQ Liue6983c72022-04-19 22:14:56 +0000871 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
872 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
873 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
874 const float rawMeanResolution =
875 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700876
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000877 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
878 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700879 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700880 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000881 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
882 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
883 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700884
Michael Wright227c5542020-07-02 18:30:52 +0100885 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700886 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700887 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
888 int32_t naturalPhysicalLeft, naturalPhysicalTop;
889 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700890
Prabir Pradhan1728b212021-10-19 16:00:03 -0700891 // Apply the inverse of the input device orientation so that the input device is
892 // configured in the same orientation as the viewport. The input device orientation will
893 // be re-applied by mInputDeviceOrientation.
894 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700895 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700896 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700897 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700898 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
899 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800900 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700901 naturalPhysicalTop = mViewport.physicalLeft;
902 naturalDeviceWidth = mViewport.deviceHeight;
903 naturalDeviceHeight = mViewport.deviceWidth;
904 break;
905 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700906 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
907 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
908 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
909 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
910 naturalDeviceWidth = mViewport.deviceWidth;
911 naturalDeviceHeight = mViewport.deviceHeight;
912 break;
913 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700914 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
915 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
916 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800917 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700918 naturalDeviceWidth = mViewport.deviceHeight;
919 naturalDeviceHeight = mViewport.deviceWidth;
920 break;
921 case DISPLAY_ORIENTATION_0:
922 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700923 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
924 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
925 naturalPhysicalLeft = mViewport.physicalLeft;
926 naturalPhysicalTop = mViewport.physicalTop;
927 naturalDeviceWidth = mViewport.deviceWidth;
928 naturalDeviceHeight = mViewport.deviceHeight;
929 break;
930 }
931
932 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
933 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
934 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
935 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
936 }
937
938 mPhysicalWidth = naturalPhysicalWidth;
939 mPhysicalHeight = naturalPhysicalHeight;
940 mPhysicalLeft = naturalPhysicalLeft;
941 mPhysicalTop = naturalPhysicalTop;
942
Prabir Pradhan1728b212021-10-19 16:00:03 -0700943 const int32_t oldDisplayWidth = mDisplayWidth;
944 const int32_t oldDisplayHeight = mDisplayHeight;
945 mDisplayWidth = naturalDeviceWidth;
946 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700947
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000948 // InputReader works in the un-rotated display coordinate space, so we don't need to do
949 // anything if the device is already orientation-aware. If the device is not
950 // orientation-aware, then we need to apply the inverse rotation of the display so that
951 // when the display rotation is applied later as a part of the per-window transform, we
952 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700953 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000954 ? DISPLAY_ORIENTATION_0
955 : getInverseRotation(mViewport.orientation);
956 // For orientation-aware devices that work in the un-rotated coordinate space, the
957 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000958 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
959 mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
960 viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700961
962 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700963 mInputDeviceOrientation =
964 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700965 } else {
966 mPhysicalWidth = rawWidth;
967 mPhysicalHeight = rawHeight;
968 mPhysicalLeft = 0;
969 mPhysicalTop = 0;
970
Prabir Pradhan1728b212021-10-19 16:00:03 -0700971 mDisplayWidth = rawWidth;
972 mDisplayHeight = rawHeight;
973 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700974 }
975 }
976
977 // If moving between pointer modes, need to reset some state.
978 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
979 if (deviceModeChanged) {
980 mOrientedRanges.clear();
981 }
982
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800983 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
984 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100985 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800986 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000987 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
988 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800989 if (mPointerController == nullptr) {
990 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700991 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000992 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800993 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
994 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700995 } else {
lilinnandef700b2022-06-17 19:32:01 +0800996 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
997 !mConfig.showTouches) {
998 mPointerController->clearSpots();
999 }
Michael Wright17db18e2020-06-26 20:51:44 +01001000 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001001 }
1002
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001003 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
1005 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -07001006 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
1007 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001009 configureVirtualKeys();
1010
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001011 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001012
1013 // Location
1014 updateAffineTransformation();
1015
Michael Wright227c5542020-07-02 18:30:52 +01001016 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001017 // Compute pointer gesture detection parameters.
1018 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001019 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001020
1021 // Scale movements such that one whole swipe of the touch pad covers a
1022 // given area relative to the diagonal size of the display when no acceleration
1023 // is applied.
1024 // Assume that the touch pad has a square aspect ratio such that movements in
1025 // X and Y of the same number of raw units cover the same physical distance.
1026 mPointerXMovementScale =
1027 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1028 mPointerYMovementScale = mPointerXMovementScale;
1029
1030 // Scale zooms to cover a smaller range of the display than movements do.
1031 // This value determines the area around the pointer that is affected by freeform
1032 // pointer gestures.
1033 mPointerXZoomScale =
1034 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1035 mPointerYZoomScale = mPointerXZoomScale;
1036
HQ Liue6983c72022-04-19 22:14:56 +00001037 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1038 // axis is non positive value.
1039 const float minFreeformGestureWidth =
1040 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1041
1042 mPointerGestureMaxSwipeWidth =
1043 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1044 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001045 }
1046
1047 // Inform the dispatcher about the changes.
1048 *outResetNeeded = true;
1049 bumpGeneration();
1050 }
1051}
1052
Prabir Pradhan1728b212021-10-19 16:00:03 -07001053void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001054 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001055 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1056 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1058 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1059 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1060 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001061 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062}
1063
1064void TouchInputMapper::configureVirtualKeys() {
1065 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001066 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067
1068 mVirtualKeys.clear();
1069
1070 if (virtualKeyDefinitions.size() == 0) {
1071 return;
1072 }
1073
1074 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1075 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1076 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1077 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1078
1079 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1080 VirtualKey virtualKey;
1081
1082 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1083 int32_t keyCode;
1084 int32_t dummyKeyMetaState;
1085 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001086 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1087 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001088 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1089 continue; // drop the key
1090 }
1091
1092 virtualKey.keyCode = keyCode;
1093 virtualKey.flags = flags;
1094
1095 // convert the key definition's display coordinates into touch coordinates for a hit box
1096 int32_t halfWidth = virtualKeyDefinition.width / 2;
1097 int32_t halfHeight = virtualKeyDefinition.height / 2;
1098
1099 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001100 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001101 touchScreenLeft;
1102 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001103 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001105 virtualKey.hitTop =
1106 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001107 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001108 virtualKey.hitBottom =
1109 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110 touchScreenTop;
1111 mVirtualKeys.push_back(virtualKey);
1112 }
1113}
1114
1115void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1116 if (!mVirtualKeys.empty()) {
1117 dump += INDENT3 "Virtual Keys:\n";
1118
1119 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1120 const VirtualKey& virtualKey = mVirtualKeys[i];
1121 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1122 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1123 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1124 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1125 }
1126 }
1127}
1128
1129void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001130 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001131 Calibration& out = mCalibration;
1132
1133 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001134 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001135 std::string sizeCalibrationString;
1136 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001148 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 }
1150 }
1151
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001152 float sizeScale;
1153
1154 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1155 out.sizeScale = sizeScale;
1156 }
1157 float sizeBias;
1158 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1159 out.sizeBias = sizeBias;
1160 }
1161 bool sizeIsSummed;
1162 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1163 out.sizeIsSummed = sizeIsSummed;
1164 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165
1166 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001168 std::string pressureCalibrationString;
1169 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (pressureCalibrationString != "default") {
1177 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001178 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 }
1180 }
1181
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001182 float pressureScale;
1183 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1184 out.pressureScale = pressureScale;
1185 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186
1187 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001189 std::string orientationCalibrationString;
1190 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001194 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 } else if (orientationCalibrationString != "default") {
1198 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001199 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 }
1201 }
1202
1203 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001205 std::string distanceCalibrationString;
1206 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 } else if (distanceCalibrationString != "default") {
1212 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001213 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 }
1215 }
1216
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001217 float distanceScale;
1218 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1219 out.distanceScale = distanceScale;
1220 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001223 std::string coverageCalibrationString;
1224 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001226 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001228 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 } else if (coverageCalibrationString != "default") {
1230 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001231 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 }
1233 }
1234}
1235
1236void TouchInputMapper::resolveCalibration() {
1237 // Size
1238 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001239 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1240 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001243 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 }
1245
1246 // Pressure
1247 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001248 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1249 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001252 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 }
1254
1255 // Orientation
1256 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001257 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1258 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001261 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263
1264 // Distance
1265 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001266 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1267 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 }
1269 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001270 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272
1273 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001274 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1275 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 }
1277}
1278
1279void TouchInputMapper::dumpCalibration(std::string& dump) {
1280 dump += INDENT3 "Calibration:\n";
1281
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001282 dump += INDENT4 "touch.size.calibration: ";
1283 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001285 if (mCalibration.sizeScale) {
1286 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 }
1288
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001289 if (mCalibration.sizeBias) {
1290 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 }
1292
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001293 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001295 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 }
1297
1298 // Pressure
1299 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001300 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += INDENT4 "touch.pressure.calibration: none\n";
1302 break;
Michael Wright227c5542020-07-02 18:30:52 +01001303 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += INDENT4 "touch.pressure.calibration: physical\n";
1305 break;
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1308 break;
1309 default:
1310 ALOG_ASSERT(false);
1311 }
1312
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001313 if (mCalibration.pressureScale) {
1314 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 }
1316
1317 // Orientation
1318 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001319 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 dump += INDENT4 "touch.orientation.calibration: none\n";
1321 break;
Michael Wright227c5542020-07-02 18:30:52 +01001322 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001323 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1324 break;
Michael Wright227c5542020-07-02 18:30:52 +01001325 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 dump += INDENT4 "touch.orientation.calibration: vector\n";
1327 break;
1328 default:
1329 ALOG_ASSERT(false);
1330 }
1331
1332 // Distance
1333 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001334 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001335 dump += INDENT4 "touch.distance.calibration: none\n";
1336 break;
Michael Wright227c5542020-07-02 18:30:52 +01001337 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 dump += INDENT4 "touch.distance.calibration: scaled\n";
1339 break;
1340 default:
1341 ALOG_ASSERT(false);
1342 }
1343
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001344 if (mCalibration.distanceScale) {
1345 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 }
1347
1348 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001349 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350 dump += INDENT4 "touch.coverage.calibration: none\n";
1351 break;
Michael Wright227c5542020-07-02 18:30:52 +01001352 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 dump += INDENT4 "touch.coverage.calibration: box\n";
1354 break;
1355 default:
1356 ALOG_ASSERT(false);
1357 }
1358}
1359
1360void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1361 dump += INDENT3 "Affine Transformation:\n";
1362
1363 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1364 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1365 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1366 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1367 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1368 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1369}
1370
1371void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001372 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001373 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374}
1375
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001376std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001377 std::list<NotifyArgs> out = cancelTouch(when, when);
1378 updateTouchSpots();
1379
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001380 mCursorButtonAccumulator.reset(getDeviceContext());
1381 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001382 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001383
1384 mPointerVelocityControl.reset();
1385 mWheelXVelocityControl.reset();
1386 mWheelYVelocityControl.reset();
1387
1388 mRawStatesPending.clear();
1389 mCurrentRawState.clear();
1390 mCurrentCookedState.clear();
1391 mLastRawState.clear();
1392 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001393 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001394 mSentHoverEnter = false;
1395 mHavePointerIds = false;
1396 mCurrentMotionAborted = false;
1397 mDownTime = 0;
1398
1399 mCurrentVirtualKey.down = false;
1400
1401 mPointerGesture.reset();
1402 mPointerSimple.reset();
1403 resetExternalStylus();
1404
1405 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001406 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407 mPointerController->clearSpots();
1408 }
1409
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001410 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411}
1412
1413void TouchInputMapper::resetExternalStylus() {
1414 mExternalStylusState.clear();
1415 mExternalStylusId = -1;
1416 mExternalStylusFusionTimeout = LLONG_MAX;
1417 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001418 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001419}
1420
1421void TouchInputMapper::clearStylusDataPendingFlags() {
1422 mExternalStylusDataPending = false;
1423 mExternalStylusFusionTimeout = LLONG_MAX;
1424}
1425
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001426std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427 mCursorButtonAccumulator.process(rawEvent);
1428 mCursorScrollAccumulator.process(rawEvent);
1429 mTouchButtonAccumulator.process(rawEvent);
1430
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001431 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001432 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001433 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001434 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001435 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436}
1437
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001438std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1439 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001440 if (mDeviceMode == DeviceMode::DISABLED) {
1441 // Only save the last pending state when the device is disabled.
1442 mRawStatesPending.clear();
1443 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 // Push a new state.
1445 mRawStatesPending.emplace_back();
1446
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001447 RawState& next = mRawStatesPending.back();
1448 next.clear();
1449 next.when = when;
1450 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451
1452 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001453 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001454 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1455
1456 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001457 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1458 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001459 mCursorScrollAccumulator.finishSync();
1460
1461 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001462 syncTouch(when, &next);
1463
1464 // The last RawState is the actually second to last, since we just added a new state
1465 const RawState& last =
1466 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001467
1468 // Assign pointer ids.
1469 if (!mHavePointerIds) {
1470 assignPointerIds(last, next);
1471 }
1472
Harry Cutts45483602022-08-24 14:36:48 +00001473 ALOGD_IF(DEBUG_RAW_EVENTS,
1474 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1475 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1476 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1477 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1478 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1479 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001480
Arthur Hung9ad18942021-06-19 02:04:46 +00001481 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1482 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1483 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1484 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1485 next.rawPointerData.hoveringIdBits.value);
1486 }
1487
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001488 out += processRawTouches(false /*timeout*/);
1489 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001490}
1491
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001492std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1493 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001494 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001495 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001496 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001497 }
1498
1499 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1500 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1501 // touching the current state will only observe the events that have been dispatched to the
1502 // rest of the pipeline.
1503 const size_t N = mRawStatesPending.size();
1504 size_t count;
1505 for (count = 0; count < N; count++) {
1506 const RawState& next = mRawStatesPending[count];
1507
1508 // A failure to assign the stylus id means that we're waiting on stylus data
1509 // and so should defer the rest of the pipeline.
1510 if (assignExternalStylusId(next, timeout)) {
1511 break;
1512 }
1513
1514 // All ready to go.
1515 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001516 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 if (mCurrentRawState.when < mLastRawState.when) {
1518 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001519 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001520 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001521 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 }
1523 if (count != 0) {
1524 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1525 }
1526
1527 if (mExternalStylusDataPending) {
1528 if (timeout) {
1529 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1530 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001531 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001532 ALOGD_IF(DEBUG_STYLUS_FUSION,
1533 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001534 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001535 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001536 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1537 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1538 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1539 }
1540 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001541 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001542}
1543
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001544std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1545 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001546 // Always start with a clean state.
1547 mCurrentCookedState.clear();
1548
1549 // Apply stylus buttons to current raw state.
1550 applyExternalStylusButtonState(when);
1551
1552 // Handle policy on initial down or hover events.
1553 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1554 mCurrentRawState.rawPointerData.pointerCount != 0;
1555
1556 uint32_t policyFlags = 0;
1557 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1558 if (initialDown || buttonsPressed) {
1559 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001560 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001561 getContext()->fadePointer();
1562 }
1563
1564 if (mParameters.wake) {
1565 policyFlags |= POLICY_FLAG_WAKE;
1566 }
1567 }
1568
1569 // Consume raw off-screen touches before cooking pointer data.
1570 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001571 bool consumed;
1572 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1573 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001574 mCurrentRawState.rawPointerData.clear();
1575 }
1576
1577 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1578 // with cooked pointer data that has the same ids and indices as the raw data.
1579 // The following code can use either the raw or cooked data, as needed.
1580 cookPointerData();
1581
1582 // Apply stylus pressure to current cooked state.
1583 applyExternalStylusTouchState(when);
1584
1585 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001586 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1587 mSource, mViewport.displayId, policyFlags,
1588 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001589
1590 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001591 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1593 uint32_t id = idBits.clearFirstMarkedBit();
1594 const RawPointerData::Pointer& pointer =
1595 mCurrentRawState.rawPointerData.pointerForId(id);
1596 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1597 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1598 mCurrentCookedState.stylusIdBits.markBit(id);
1599 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1600 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1601 mCurrentCookedState.fingerIdBits.markBit(id);
1602 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1603 mCurrentCookedState.mouseIdBits.markBit(id);
1604 }
1605 }
1606 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1607 uint32_t id = idBits.clearFirstMarkedBit();
1608 const RawPointerData::Pointer& pointer =
1609 mCurrentRawState.rawPointerData.pointerForId(id);
1610 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1611 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1612 mCurrentCookedState.stylusIdBits.markBit(id);
1613 }
1614 }
1615
1616 // Stylus takes precedence over all tools, then mouse, then finger.
1617 PointerUsage pointerUsage = mPointerUsage;
1618 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1619 mCurrentCookedState.mouseIdBits.clear();
1620 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001621 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001622 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1623 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001624 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1626 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001627 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 }
1629
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001630 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001631 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001633 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001634 out += dispatchButtonRelease(when, readTime, policyFlags);
1635 out += dispatchHoverExit(when, readTime, policyFlags);
1636 out += dispatchTouches(when, readTime, policyFlags);
1637 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1638 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001639 }
1640
1641 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1642 mCurrentMotionAborted = false;
1643 }
1644 }
1645
1646 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001647 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1648 mSource, mViewport.displayId, policyFlags,
1649 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001650
1651 // Clear some transient state.
1652 mCurrentRawState.rawVScroll = 0;
1653 mCurrentRawState.rawHScroll = 0;
1654
1655 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001656 mLastRawState = mCurrentRawState;
1657 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001658 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001659}
1660
Garfield Tanc734e4f2021-01-15 20:01:39 -08001661void TouchInputMapper::updateTouchSpots() {
1662 if (!mConfig.showTouches || mPointerController == nullptr) {
1663 return;
1664 }
1665
1666 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1667 // clear touch spots.
1668 if (mDeviceMode != DeviceMode::DIRECT &&
1669 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1670 return;
1671 }
1672
1673 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1674 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1675
1676 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001677 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1678 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001679 mCurrentCookedState.cookedPointerData.touchingIdBits,
1680 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001681}
1682
1683bool TouchInputMapper::isTouchScreen() {
1684 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1685 mParameters.hasAssociatedDisplay;
1686}
1687
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001688void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001689 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1690 // If any of the external buttons are already pressed by the touch device, ignore them.
1691 const int32_t pressedButtons = ~mCurrentRawState.buttonState & mExternalStylusState.buttons;
1692 const int32_t releasedButtons =
1693 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1694
1695 mCurrentRawState.buttonState |= pressedButtons;
1696 mCurrentRawState.buttonState &= ~releasedButtons;
1697
1698 mExternalStylusButtonsApplied |= pressedButtons;
1699 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001700 }
1701}
1702
1703void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1704 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1705 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1706
1707 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1708 float pressure = mExternalStylusState.pressure;
1709 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1710 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1711 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1712 }
1713 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1714 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1715
1716 PointerProperties& properties =
1717 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1718 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1719 properties.toolType = mExternalStylusState.toolType;
1720 }
1721 }
1722}
1723
1724bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001725 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001726 return false;
1727 }
1728
1729 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1730 state.rawPointerData.pointerCount != 0;
1731 if (initialDown) {
1732 if (mExternalStylusState.pressure != 0.0f) {
Harry Cutts45483602022-08-24 14:36:48 +00001733 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001734 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1735 } else if (timeout) {
Harry Cutts45483602022-08-24 14:36:48 +00001736 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
Prabir Pradhan124ea442022-10-28 20:27:44 +00001737 mExternalStylusId = -1;
1738 mExternalStylusFusionTimeout = LLONG_MAX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001739 } else {
1740 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1741 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1742 }
Harry Cutts45483602022-08-24 14:36:48 +00001743 ALOGD_IF(DEBUG_STYLUS_FUSION,
1744 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1745 mExternalStylusFusionTimeout);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001746 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1747 return true;
1748 }
1749 }
1750
1751 // Check if the stylus pointer has gone up.
1752 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001753 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001754 mExternalStylusId = -1;
1755 }
1756
1757 return false;
1758}
1759
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001760std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1761 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001762 if (mDeviceMode == DeviceMode::POINTER) {
1763 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001764 // Since this is a synthetic event, we can consider its latency to be zero
1765 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001766 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001767 }
Michael Wright227c5542020-07-02 18:30:52 +01001768 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001769 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001770 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001771 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1772 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1773 }
1774 }
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::updateExternalStylusState(const StylusState& state) {
1779 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001780 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001781 mExternalStylusState.copyFrom(state);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001782 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
1783 // The following three cases are handled here:
1784 // - We're in the middle of a fused stream of data;
1785 // - We're waiting on external stylus data before dispatching the initial down; or
1786 // - Only the button state, which is not reported through a specific pointer, has changed.
1787 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001788 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001789 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001790 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001791 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792}
1793
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001794std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1795 uint32_t policyFlags, bool& outConsumed) {
1796 outConsumed = false;
1797 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001798 // Check for release of a virtual key.
1799 if (mCurrentVirtualKey.down) {
1800 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1801 // Pointer went up while virtual key was down.
1802 mCurrentVirtualKey.down = false;
1803 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001804 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1805 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1806 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001807 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1808 AKEY_EVENT_FLAG_FROM_SYSTEM |
1809 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001810 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001811 outConsumed = true;
1812 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001813 }
1814
1815 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1816 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1817 const RawPointerData::Pointer& pointer =
1818 mCurrentRawState.rawPointerData.pointerForId(id);
1819 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1820 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1821 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001822 outConsumed = true;
1823 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001824 }
1825 }
1826
1827 // Pointer left virtual key area or another pointer also went down.
1828 // Send key cancellation but do not consume the touch yet.
1829 // This is useful when the user swipes through from the virtual key area
1830 // into the main display surface.
1831 mCurrentVirtualKey.down = false;
1832 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001833 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1834 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001835 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1836 AKEY_EVENT_FLAG_FROM_SYSTEM |
1837 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1838 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001839 }
1840 }
1841
1842 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1843 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1844 // Pointer just went down. Check for virtual key press or off-screen touches.
1845 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1846 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001847 // Skip checking whether the pointer is inside the physical frame if the device is in
1848 // unscaled mode.
1849 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1850 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001851 // If exactly one pointer went down, check for virtual key hit.
1852 // Otherwise we will drop the entire stroke.
1853 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1854 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1855 if (virtualKey) {
1856 mCurrentVirtualKey.down = true;
1857 mCurrentVirtualKey.downTime = when;
1858 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1859 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1860 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001861 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1862 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001863
1864 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001865 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1866 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1867 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001868 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1869 AKEY_EVENT_ACTION_DOWN,
1870 AKEY_EVENT_FLAG_FROM_SYSTEM |
1871 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001872 }
1873 }
1874 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001875 outConsumed = true;
1876 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001877 }
1878 }
1879
1880 // Disable all virtual key touches that happen within a short time interval of the
1881 // most recent touch within the screen area. The idea is to filter out stray
1882 // virtual key presses when interacting with the touch screen.
1883 //
1884 // Problems we're trying to solve:
1885 //
1886 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1887 // virtual key area that is implemented by a separate touch panel and accidentally
1888 // triggers a virtual key.
1889 //
1890 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1891 // area and accidentally triggers a virtual key. This often happens when virtual keys
1892 // are layed out below the screen near to where the on screen keyboard's space bar
1893 // is displayed.
1894 if (mConfig.virtualKeyQuietTime > 0 &&
1895 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001896 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001897 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001898 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001899}
1900
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001901NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1902 uint32_t policyFlags, int32_t keyEventAction,
1903 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001904 int32_t keyCode = mCurrentVirtualKey.keyCode;
1905 int32_t scanCode = mCurrentVirtualKey.scanCode;
1906 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001907 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001908 policyFlags |= POLICY_FLAG_VIRTUAL;
1909
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001910 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1911 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1912 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001913}
1914
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001915std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1916 uint32_t policyFlags) {
1917 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001918 if (mCurrentMotionAborted) {
1919 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001921 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001922 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1923 if (!currentIdBits.isEmpty()) {
1924 int32_t metaState = getContext()->getGlobalMetaState();
1925 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001926 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001927 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1928 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001929 mCurrentCookedState.cookedPointerData.pointerProperties,
1930 mCurrentCookedState.cookedPointerData.pointerCoords,
1931 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1932 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1933 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001934 mCurrentMotionAborted = true;
1935 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001936 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001937}
1938
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001939// Updates pointer coords and properties for pointers with specified ids that have moved.
1940// Returns true if any of them changed.
1941static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1942 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1943 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1944 BitSet32 idBits) {
1945 bool changed = false;
1946 while (!idBits.isEmpty()) {
1947 uint32_t id = idBits.clearFirstMarkedBit();
1948 uint32_t inIndex = inIdToIndex[id];
1949 uint32_t outIndex = outIdToIndex[id];
1950
1951 const PointerProperties& curInProperties = inProperties[inIndex];
1952 const PointerCoords& curInCoords = inCoords[inIndex];
1953 PointerProperties& curOutProperties = outProperties[outIndex];
1954 PointerCoords& curOutCoords = outCoords[outIndex];
1955
1956 if (curInProperties != curOutProperties) {
1957 curOutProperties.copyFrom(curInProperties);
1958 changed = true;
1959 }
1960
1961 if (curInCoords != curOutCoords) {
1962 curOutCoords.copyFrom(curInCoords);
1963 changed = true;
1964 }
1965 }
1966 return changed;
1967}
1968
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001969std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1970 uint32_t policyFlags) {
1971 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001972 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1973 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1974 int32_t metaState = getContext()->getGlobalMetaState();
1975 int32_t buttonState = mCurrentCookedState.buttonState;
1976
1977 if (currentIdBits == lastIdBits) {
1978 if (!currentIdBits.isEmpty()) {
1979 // No pointer id changes so this is a move event.
1980 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001981 out.push_back(
1982 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1983 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1984 mCurrentCookedState.cookedPointerData.pointerProperties,
1985 mCurrentCookedState.cookedPointerData.pointerCoords,
1986 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1987 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1988 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001989 }
1990 } else {
1991 // There may be pointers going up and pointers going down and pointers moving
1992 // all at the same time.
1993 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1994 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1995 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1996 BitSet32 dispatchedIdBits(lastIdBits.value);
1997
1998 // Update last coordinates of pointers that have moved so that we observe the new
1999 // pointer positions at the same time as other pointers that have just gone up.
2000 bool moveNeeded =
2001 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2002 mCurrentCookedState.cookedPointerData.pointerCoords,
2003 mCurrentCookedState.cookedPointerData.idToIndex,
2004 mLastCookedState.cookedPointerData.pointerProperties,
2005 mLastCookedState.cookedPointerData.pointerCoords,
2006 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2007 if (buttonState != mLastCookedState.buttonState) {
2008 moveNeeded = true;
2009 }
2010
2011 // Dispatch pointer up events.
2012 while (!upIdBits.isEmpty()) {
2013 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002014 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002015 if (isCanceled) {
2016 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2017 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002018 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2019 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2020 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2021 buttonState, 0,
2022 mLastCookedState.cookedPointerData.pointerProperties,
2023 mLastCookedState.cookedPointerData.pointerCoords,
2024 mLastCookedState.cookedPointerData.idToIndex,
2025 dispatchedIdBits, upId, mOrientedXPrecision,
2026 mOrientedYPrecision, mDownTime,
2027 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002028 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002029 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002030 }
2031
2032 // Dispatch move events if any of the remaining pointers moved from their old locations.
2033 // Although applications receive new locations as part of individual pointer up
2034 // events, they do not generally handle them except when presented in a move event.
2035 if (moveNeeded && !moveIdBits.isEmpty()) {
2036 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002037 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2038 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2039 mCurrentCookedState.cookedPointerData.pointerProperties,
2040 mCurrentCookedState.cookedPointerData.pointerCoords,
2041 mCurrentCookedState.cookedPointerData.idToIndex,
2042 dispatchedIdBits, -1, mOrientedXPrecision,
2043 mOrientedYPrecision, mDownTime,
2044 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002045 }
2046
2047 // Dispatch pointer down events using the new pointer locations.
2048 while (!downIdBits.isEmpty()) {
2049 uint32_t downId = downIdBits.clearFirstMarkedBit();
2050 dispatchedIdBits.markBit(downId);
2051
2052 if (dispatchedIdBits.count() == 1) {
2053 // First pointer is going down. Set down time.
2054 mDownTime = when;
2055 }
2056
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002057 out.push_back(
2058 dispatchMotion(when, readTime, policyFlags, mSource,
2059 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2060 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2061 mCurrentCookedState.cookedPointerData.pointerCoords,
2062 mCurrentCookedState.cookedPointerData.idToIndex,
2063 dispatchedIdBits, downId, mOrientedXPrecision,
2064 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002065 }
2066 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002067 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002068}
2069
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002070std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2071 uint32_t policyFlags) {
2072 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002073 if (mSentHoverEnter &&
2074 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2075 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2076 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002077 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2078 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2079 mLastCookedState.buttonState, 0,
2080 mLastCookedState.cookedPointerData.pointerProperties,
2081 mLastCookedState.cookedPointerData.pointerCoords,
2082 mLastCookedState.cookedPointerData.idToIndex,
2083 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2084 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2085 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002086 mSentHoverEnter = false;
2087 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002088 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089}
2090
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002091std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2092 uint32_t policyFlags) {
2093 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002094 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2095 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2096 int32_t metaState = getContext()->getGlobalMetaState();
2097 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002098 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2099 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2100 mCurrentRawState.buttonState, 0,
2101 mCurrentCookedState.cookedPointerData.pointerProperties,
2102 mCurrentCookedState.cookedPointerData.pointerCoords,
2103 mCurrentCookedState.cookedPointerData.idToIndex,
2104 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2105 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2106 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002107 mSentHoverEnter = true;
2108 }
2109
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002110 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2111 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2112 mCurrentRawState.buttonState, 0,
2113 mCurrentCookedState.cookedPointerData.pointerProperties,
2114 mCurrentCookedState.cookedPointerData.pointerCoords,
2115 mCurrentCookedState.cookedPointerData.idToIndex,
2116 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2117 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2118 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002119 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002120 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002121}
2122
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002123std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2124 uint32_t policyFlags) {
2125 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002126 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2127 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2128 const int32_t metaState = getContext()->getGlobalMetaState();
2129 int32_t buttonState = mLastCookedState.buttonState;
2130 while (!releasedButtons.isEmpty()) {
2131 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2132 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002133 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2134 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2135 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002136 mLastCookedState.cookedPointerData.pointerProperties,
2137 mLastCookedState.cookedPointerData.pointerCoords,
2138 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002139 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2140 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002142 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002143}
2144
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002145std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2146 uint32_t policyFlags) {
2147 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002148 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2149 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2150 const int32_t metaState = getContext()->getGlobalMetaState();
2151 int32_t buttonState = mLastCookedState.buttonState;
2152 while (!pressedButtons.isEmpty()) {
2153 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2154 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002155 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2156 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2157 buttonState, 0,
2158 mCurrentCookedState.cookedPointerData.pointerProperties,
2159 mCurrentCookedState.cookedPointerData.pointerCoords,
2160 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2161 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2162 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002164 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165}
2166
2167const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2168 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2169 return cookedPointerData.touchingIdBits;
2170 }
2171 return cookedPointerData.hoveringIdBits;
2172}
2173
2174void TouchInputMapper::cookPointerData() {
2175 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2176
2177 mCurrentCookedState.cookedPointerData.clear();
2178 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2179 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2180 mCurrentRawState.rawPointerData.hoveringIdBits;
2181 mCurrentCookedState.cookedPointerData.touchingIdBits =
2182 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002183 mCurrentCookedState.cookedPointerData.canceledIdBits =
2184 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185
2186 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2187 mCurrentCookedState.buttonState = 0;
2188 } else {
2189 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2190 }
2191
2192 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002193 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002194 for (uint32_t i = 0; i < currentPointerCount; i++) {
2195 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2196
2197 // Size
2198 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2199 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002200 case Calibration::SizeCalibration::GEOMETRIC:
2201 case Calibration::SizeCalibration::DIAMETER:
2202 case Calibration::SizeCalibration::BOX:
2203 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002204 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2205 touchMajor = in.touchMajor;
2206 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2207 toolMajor = in.toolMajor;
2208 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2209 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2210 : in.touchMajor;
2211 } else if (mRawPointerAxes.touchMajor.valid) {
2212 toolMajor = touchMajor = in.touchMajor;
2213 toolMinor = touchMinor =
2214 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2215 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2216 : in.touchMajor;
2217 } else if (mRawPointerAxes.toolMajor.valid) {
2218 touchMajor = toolMajor = in.toolMajor;
2219 touchMinor = toolMinor =
2220 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2221 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2222 : in.toolMajor;
2223 } else {
2224 ALOG_ASSERT(false,
2225 "No touch or tool axes. "
2226 "Size calibration should have been resolved to NONE.");
2227 touchMajor = 0;
2228 touchMinor = 0;
2229 toolMajor = 0;
2230 toolMinor = 0;
2231 size = 0;
2232 }
2233
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002234 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002235 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2236 if (touchingCount > 1) {
2237 touchMajor /= touchingCount;
2238 touchMinor /= touchingCount;
2239 toolMajor /= touchingCount;
2240 toolMinor /= touchingCount;
2241 size /= touchingCount;
2242 }
2243 }
2244
Michael Wright227c5542020-07-02 18:30:52 +01002245 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002246 touchMajor *= mGeometricScale;
2247 touchMinor *= mGeometricScale;
2248 toolMajor *= mGeometricScale;
2249 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002250 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002251 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2252 touchMinor = touchMajor;
2253 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2254 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002255 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 touchMinor = touchMajor;
2257 toolMinor = toolMajor;
2258 }
2259
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002260 mCalibration.applySizeScaleAndBias(touchMajor);
2261 mCalibration.applySizeScaleAndBias(touchMinor);
2262 mCalibration.applySizeScaleAndBias(toolMajor);
2263 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002264 size *= mSizeScale;
2265 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002266 case Calibration::SizeCalibration::DEFAULT:
2267 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2268 break;
2269 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002270 touchMajor = 0;
2271 touchMinor = 0;
2272 toolMajor = 0;
2273 toolMinor = 0;
2274 size = 0;
2275 break;
2276 }
2277
2278 // Pressure
2279 float pressure;
2280 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002281 case Calibration::PressureCalibration::PHYSICAL:
2282 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002283 pressure = in.pressure * mPressureScale;
2284 break;
2285 default:
2286 pressure = in.isHovering ? 0 : 1;
2287 break;
2288 }
2289
2290 // Tilt and Orientation
2291 float tilt;
2292 float orientation;
2293 if (mHaveTilt) {
2294 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2295 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2296 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2297 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2298 } else {
2299 tilt = 0;
2300
2301 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002302 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 orientation = in.orientation * mOrientationScale;
2304 break;
Michael Wright227c5542020-07-02 18:30:52 +01002305 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002306 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2307 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2308 if (c1 != 0 || c2 != 0) {
2309 orientation = atan2f(c1, c2) * 0.5f;
2310 float confidence = hypotf(c1, c2);
2311 float scale = 1.0f + confidence / 16.0f;
2312 touchMajor *= scale;
2313 touchMinor /= scale;
2314 toolMajor *= scale;
2315 toolMinor /= scale;
2316 } else {
2317 orientation = 0;
2318 }
2319 break;
2320 }
2321 default:
2322 orientation = 0;
2323 }
2324 }
2325
2326 // Distance
2327 float distance;
2328 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002329 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002330 distance = in.distance * mDistanceScale;
2331 break;
2332 default:
2333 distance = 0;
2334 }
2335
2336 // Coverage
2337 int32_t rawLeft, rawTop, rawRight, rawBottom;
2338 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002339 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002340 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2341 rawRight = in.toolMinor & 0x0000ffff;
2342 rawBottom = in.toolMajor & 0x0000ffff;
2343 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2344 break;
2345 default:
2346 rawLeft = rawTop = rawRight = rawBottom = 0;
2347 break;
2348 }
2349
2350 // Adjust X,Y coords for device calibration
2351 // TODO: Adjust coverage coords?
2352 float xTransformed = in.x, yTransformed = in.y;
2353 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002354 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355
Prabir Pradhan1728b212021-10-19 16:00:03 -07002356 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002357 float left, top, right, bottom;
2358
Prabir Pradhan1728b212021-10-19 16:00:03 -07002359 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002360 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002361 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2362 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2363 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2364 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002366 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002368 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 }
2370 break;
2371 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2373 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002374 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2375 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002376 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002377 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002379 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 }
2381 break;
2382 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2384 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002385 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2386 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002388 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002390 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 }
2392 break;
2393 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002394 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2395 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2396 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2397 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 break;
2399 }
2400
2401 // Write output coords.
2402 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2403 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002404 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2405 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2407 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2408 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2409 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2410 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2411 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2412 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002413 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002414 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2415 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2416 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2417 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2418 } else {
2419 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2420 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2421 }
2422
Chris Ye364fdb52020-08-05 15:07:56 -07002423 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002424 uint32_t id = in.id;
2425 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2426 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2427 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2428 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2429 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2430 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2431 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2432 }
2433
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 // Write output properties.
2435 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 properties.clear();
2437 properties.id = id;
2438 properties.toolType = in.toolType;
2439
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002440 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002441 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002442 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 }
2444}
2445
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002446std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2447 uint32_t policyFlags,
2448 PointerUsage pointerUsage) {
2449 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002451 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452 mPointerUsage = pointerUsage;
2453 }
2454
2455 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002456 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002457 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 break;
Michael Wright227c5542020-07-02 18:30:52 +01002459 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002460 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 break;
Michael Wright227c5542020-07-02 18:30:52 +01002462 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002463 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 break;
Michael Wright227c5542020-07-02 18:30:52 +01002465 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 break;
2467 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002468 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469}
2470
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002471std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2472 uint32_t policyFlags) {
2473 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002475 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002476 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002477 break;
Michael Wright227c5542020-07-02 18:30:52 +01002478 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002479 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 break;
Michael Wright227c5542020-07-02 18:30:52 +01002481 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002482 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483 break;
Michael Wright227c5542020-07-02 18:30:52 +01002484 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 break;
2486 }
2487
Michael Wright227c5542020-07-02 18:30:52 +01002488 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002489 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490}
2491
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002492std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2493 uint32_t policyFlags,
2494 bool isTimeout) {
2495 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496 // Update current gesture coordinates.
2497 bool cancelPreviousGesture, finishPreviousGesture;
2498 bool sendEvents =
2499 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2500 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002501 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 }
2503 if (finishPreviousGesture) {
2504 cancelPreviousGesture = false;
2505 }
2506
2507 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002508 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002509 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002510 if (finishPreviousGesture || cancelPreviousGesture) {
2511 mPointerController->clearSpots();
2512 }
2513
Michael Wright227c5542020-07-02 18:30:52 +01002514 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002515 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2516 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002517 mPointerGesture.currentGestureIdBits,
2518 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002519 }
2520 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002521 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 }
2523
2524 // Show or hide the pointer if needed.
2525 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002526 case PointerGesture::Mode::NEUTRAL:
2527 case PointerGesture::Mode::QUIET:
2528 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2529 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002530 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002531 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002532 }
2533 break;
Michael Wright227c5542020-07-02 18:30:52 +01002534 case PointerGesture::Mode::TAP:
2535 case PointerGesture::Mode::TAP_DRAG:
2536 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2537 case PointerGesture::Mode::HOVER:
2538 case PointerGesture::Mode::PRESS:
2539 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002540 // Unfade the pointer when the current gesture manipulates the
2541 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002542 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002543 break;
Michael Wright227c5542020-07-02 18:30:52 +01002544 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002545 // Fade the pointer when the current gesture manipulates a different
2546 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002547 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002548 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002549 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002550 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002551 }
2552 break;
2553 }
2554
2555 // Send events!
2556 int32_t metaState = getContext()->getGlobalMetaState();
2557 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002558 const MotionClassification classification =
2559 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2560 ? MotionClassification::TWO_FINGER_SWIPE
2561 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002562
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002563 uint32_t flags = 0;
2564
2565 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2566 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2567 }
2568
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002569 // Update last coordinates of pointers that have moved so that we observe the new
2570 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002571 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2572 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2573 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2574 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2575 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2576 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002577 bool moveNeeded = false;
2578 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2579 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2580 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2581 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2582 mPointerGesture.lastGestureIdBits.value);
2583 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2584 mPointerGesture.currentGestureCoords,
2585 mPointerGesture.currentGestureIdToIndex,
2586 mPointerGesture.lastGestureProperties,
2587 mPointerGesture.lastGestureCoords,
2588 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2589 if (buttonState != mLastCookedState.buttonState) {
2590 moveNeeded = true;
2591 }
2592 }
2593
2594 // Send motion events for all pointers that went up or were canceled.
2595 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2596 if (!dispatchedGestureIdBits.isEmpty()) {
2597 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002598 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002599 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002600 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002601 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2602 mPointerGesture.lastGestureProperties,
2603 mPointerGesture.lastGestureCoords,
2604 mPointerGesture.lastGestureIdToIndex,
2605 dispatchedGestureIdBits, -1, 0, 0,
2606 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002607
2608 dispatchedGestureIdBits.clear();
2609 } else {
2610 BitSet32 upGestureIdBits;
2611 if (finishPreviousGesture) {
2612 upGestureIdBits = dispatchedGestureIdBits;
2613 } else {
2614 upGestureIdBits.value =
2615 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2616 }
2617 while (!upGestureIdBits.isEmpty()) {
2618 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2619
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002620 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2621 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2622 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2623 mPointerGesture.lastGestureProperties,
2624 mPointerGesture.lastGestureCoords,
2625 mPointerGesture.lastGestureIdToIndex,
2626 dispatchedGestureIdBits, id, 0, 0,
2627 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002628
2629 dispatchedGestureIdBits.clearBit(id);
2630 }
2631 }
2632 }
2633
2634 // Send motion events for all pointers that moved.
2635 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002636 out.push_back(
2637 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2638 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2639 mPointerGesture.currentGestureProperties,
2640 mPointerGesture.currentGestureCoords,
2641 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2642 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002643 }
2644
2645 // Send motion events for all pointers that went down.
2646 if (down) {
2647 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2648 ~dispatchedGestureIdBits.value);
2649 while (!downGestureIdBits.isEmpty()) {
2650 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2651 dispatchedGestureIdBits.markBit(id);
2652
2653 if (dispatchedGestureIdBits.count() == 1) {
2654 mPointerGesture.downTime = when;
2655 }
2656
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002657 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2658 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2659 buttonState, 0, mPointerGesture.currentGestureProperties,
2660 mPointerGesture.currentGestureCoords,
2661 mPointerGesture.currentGestureIdToIndex,
2662 dispatchedGestureIdBits, id, 0, 0,
2663 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002664 }
2665 }
2666
2667 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002668 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002669 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2670 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2671 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2672 mPointerGesture.currentGestureProperties,
2673 mPointerGesture.currentGestureCoords,
2674 mPointerGesture.currentGestureIdToIndex,
2675 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2676 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002677 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2678 // Synthesize a hover move event after all pointers go up to indicate that
2679 // the pointer is hovering again even if the user is not currently touching
2680 // the touch pad. This ensures that a view will receive a fresh hover enter
2681 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002682 float x, y;
2683 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002684
2685 PointerProperties pointerProperties;
2686 pointerProperties.clear();
2687 pointerProperties.id = 0;
2688 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2689
2690 PointerCoords pointerCoords;
2691 pointerCoords.clear();
2692 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2693 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2694
2695 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002696 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2697 mSource, displayId, policyFlags,
2698 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2699 buttonState, MotionClassification::NONE,
2700 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2701 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2702 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002703 }
2704
2705 // Update state.
2706 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2707 if (!down) {
2708 mPointerGesture.lastGestureIdBits.clear();
2709 } else {
2710 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2711 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2712 uint32_t id = idBits.clearFirstMarkedBit();
2713 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2714 mPointerGesture.lastGestureProperties[index].copyFrom(
2715 mPointerGesture.currentGestureProperties[index]);
2716 mPointerGesture.lastGestureCoords[index].copyFrom(
2717 mPointerGesture.currentGestureCoords[index]);
2718 mPointerGesture.lastGestureIdToIndex[id] = index;
2719 }
2720 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002721 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002722}
2723
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002724std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2725 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002726 const MotionClassification classification =
2727 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2728 ? MotionClassification::TWO_FINGER_SWIPE
2729 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002730 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002731 // Cancel previously dispatches pointers.
2732 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2733 int32_t metaState = getContext()->getGlobalMetaState();
2734 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002735 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002736 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2737 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002738 mPointerGesture.lastGestureProperties,
2739 mPointerGesture.lastGestureCoords,
2740 mPointerGesture.lastGestureIdToIndex,
2741 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2742 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002743 }
2744
2745 // Reset the current pointer gesture.
2746 mPointerGesture.reset();
2747 mPointerVelocityControl.reset();
2748
2749 // Remove any current spots.
2750 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002751 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002752 mPointerController->clearSpots();
2753 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002754 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002755}
2756
2757bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2758 bool* outFinishPreviousGesture, bool isTimeout) {
2759 *outCancelPreviousGesture = false;
2760 *outFinishPreviousGesture = false;
2761
2762 // Handle TAP timeout.
2763 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002764 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002765
Michael Wright227c5542020-07-02 18:30:52 +01002766 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002767 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2768 // The tap/drag timeout has not yet expired.
2769 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2770 mConfig.pointerGestureTapDragInterval);
2771 } else {
2772 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002773 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002774 *outFinishPreviousGesture = true;
2775
2776 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002777 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002778 mPointerGesture.currentGestureIdBits.clear();
2779
2780 mPointerVelocityControl.reset();
2781 return true;
2782 }
2783 }
2784
2785 // We did not handle this timeout.
2786 return false;
2787 }
2788
2789 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2790 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2791
2792 // Update the velocity tracker.
2793 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002794 std::vector<float> positionsX;
2795 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002796 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 uint32_t id = idBits.clearFirstMarkedBit();
2798 const RawPointerData::Pointer& pointer =
2799 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002800 positionsX.push_back(pointer.x * mPointerXMovementScale);
2801 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002802 }
2803 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002804 {{AMOTION_EVENT_AXIS_X, positionsX},
2805 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 }
2807
2808 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2809 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002810 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2811 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2812 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002813 mPointerGesture.resetTap();
2814 }
2815
2816 // Pick a new active touch id if needed.
2817 // Choose an arbitrary pointer that just went down, if there is one.
2818 // Otherwise choose an arbitrary remaining pointer.
2819 // This guarantees we always have an active touch id when there is at least one pointer.
2820 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002821 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002823 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824 mPointerGesture.firstTouchTime = when;
2825 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002826 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2827 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2828 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2829 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002831 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002832
2833 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002834 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002835 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002836 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2837 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2838 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002839 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002840 *outFinishPreviousGesture = true;
2841 }
2842
2843 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002844 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002845 mPointerGesture.currentGestureIdBits.clear();
2846
2847 mPointerVelocityControl.reset();
2848 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2849 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2850 // The pointer follows the active touch point.
2851 // Emit DOWN, MOVE, UP events at the pointer location.
2852 //
2853 // Only the active touch matters; other fingers are ignored. This policy helps
2854 // to handle the case where the user places a second finger on the touch pad
2855 // to apply the necessary force to depress an integrated button below the surface.
2856 // We don't want the second finger to be delivered to applications.
2857 //
2858 // For this to work well, we need to make sure to track the pointer that is really
2859 // active. If the user first puts one finger down to click then adds another
2860 // finger to drag then the active pointer should switch to the finger that is
2861 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002862 ALOGD_IF(DEBUG_GESTURES,
2863 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2864 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002866 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 *outFinishPreviousGesture = true;
2868 mPointerGesture.activeGestureId = 0;
2869 }
2870
2871 // Switch pointers if needed.
2872 // Find the fastest pointer and follow it.
2873 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002874 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002876 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002877 ALOGD_IF(DEBUG_GESTURES,
2878 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2879 "bestSpeed=%0.3f",
2880 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002881 }
2882 }
2883
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885 // When using spots, the click will occur at the position of the anchor
2886 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002887 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002888 } else {
2889 mPointerVelocityControl.reset();
2890 }
2891
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002892 float x, y;
2893 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002894
Michael Wright227c5542020-07-02 18:30:52 +01002895 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002896 mPointerGesture.currentGestureIdBits.clear();
2897 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2898 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2899 mPointerGesture.currentGestureProperties[0].clear();
2900 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2901 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2902 mPointerGesture.currentGestureCoords[0].clear();
2903 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2904 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2905 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2906 } else if (currentFingerCount == 0) {
2907 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002908 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002909 *outFinishPreviousGesture = true;
2910 }
2911
2912 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2913 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2914 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002915 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2916 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002917 lastFingerCount == 1) {
2918 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002919 float x, y;
2920 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002921 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2922 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002923 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002924
2925 mPointerGesture.tapUpTime = when;
2926 getContext()->requestTimeoutAtTime(when +
2927 mConfig.pointerGestureTapDragInterval);
2928
2929 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002930 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002931 mPointerGesture.currentGestureIdBits.clear();
2932 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2933 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2934 mPointerGesture.currentGestureProperties[0].clear();
2935 mPointerGesture.currentGestureProperties[0].id =
2936 mPointerGesture.activeGestureId;
2937 mPointerGesture.currentGestureProperties[0].toolType =
2938 AMOTION_EVENT_TOOL_TYPE_FINGER;
2939 mPointerGesture.currentGestureCoords[0].clear();
2940 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2941 mPointerGesture.tapX);
2942 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2943 mPointerGesture.tapY);
2944 mPointerGesture.currentGestureCoords[0]
2945 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2946
2947 tapped = true;
2948 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002949 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2950 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 }
2952 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002953 if (DEBUG_GESTURES) {
2954 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2955 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2956 (when - mPointerGesture.tapDownTime) * 0.000001f);
2957 } else {
2958 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2959 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002960 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002961 }
2962 }
2963
2964 mPointerVelocityControl.reset();
2965
2966 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002967 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002969 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 mPointerGesture.currentGestureIdBits.clear();
2971 }
2972 } else if (currentFingerCount == 1) {
2973 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2974 // The pointer follows the active touch point.
2975 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2976 // When in TAP_DRAG, emit MOVE events at the pointer location.
2977 ALOG_ASSERT(activeTouchId >= 0);
2978
Michael Wright227c5542020-07-02 18:30:52 +01002979 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2980 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002982 float x, y;
2983 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2985 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002986 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002987 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002988 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2989 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 }
2991 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002992 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2993 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002994 }
Michael Wright227c5542020-07-02 18:30:52 +01002995 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2996 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 }
2998
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002999 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003000 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003001 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003002 } else {
3003 mPointerVelocityControl.reset();
3004 }
3005
3006 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003007 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003008 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003009 down = true;
3010 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003011 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003012 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003013 *outFinishPreviousGesture = true;
3014 }
3015 mPointerGesture.activeGestureId = 0;
3016 down = false;
3017 }
3018
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003019 float x, y;
3020 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003021
3022 mPointerGesture.currentGestureIdBits.clear();
3023 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3024 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3025 mPointerGesture.currentGestureProperties[0].clear();
3026 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3027 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3028 mPointerGesture.currentGestureCoords[0].clear();
3029 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3030 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3031 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3032 down ? 1.0f : 0.0f);
3033
3034 if (lastFingerCount == 0 && currentFingerCount != 0) {
3035 mPointerGesture.resetTap();
3036 mPointerGesture.tapDownTime = when;
3037 mPointerGesture.tapX = x;
3038 mPointerGesture.tapY = y;
3039 }
3040 } else {
3041 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003042 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003043 }
3044
3045 mPointerController->setButtonState(mCurrentRawState.buttonState);
3046
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003047 if (DEBUG_GESTURES) {
3048 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3049 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3050 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3051 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3052 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3053 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3054 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3055 uint32_t id = idBits.clearFirstMarkedBit();
3056 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3057 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3058 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3059 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3060 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3061 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3062 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3063 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3064 }
3065 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3066 uint32_t id = idBits.clearFirstMarkedBit();
3067 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3068 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3069 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3070 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3071 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3072 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3073 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3074 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3075 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003076 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003077 return true;
3078}
3079
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003080bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3081 if (mPointerGesture.activeTouchId < 0) {
3082 mPointerGesture.resetQuietTime();
3083 return false;
3084 }
3085
3086 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3087 return true;
3088 }
3089
3090 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3091 bool isQuietTime = false;
3092 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3093 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3094 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3095 currentFingerCount < 2) {
3096 // Enter quiet time when exiting swipe or freeform state.
3097 // This is to prevent accidentally entering the hover state and flinging the
3098 // pointer when finishing a swipe and there is still one pointer left onscreen.
3099 isQuietTime = true;
3100 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3101 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3102 // Enter quiet time when releasing the button and there are still two or more
3103 // fingers down. This may indicate that one finger was used to press the button
3104 // but it has not gone up yet.
3105 isQuietTime = true;
3106 }
3107 if (isQuietTime) {
3108 mPointerGesture.quietTime = when;
3109 }
3110 return isQuietTime;
3111}
3112
3113std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3114 int32_t bestId = -1;
3115 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3116 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3117 uint32_t id = idBits.clearFirstMarkedBit();
3118 std::optional<float> vx =
3119 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3120 std::optional<float> vy =
3121 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3122 if (vx && vy) {
3123 float speed = hypotf(*vx, *vy);
3124 if (speed > bestSpeed) {
3125 bestId = id;
3126 bestSpeed = speed;
3127 }
3128 }
3129 }
3130 return std::make_pair(bestId, bestSpeed);
3131}
3132
3133void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3134 bool* finishPreviousGesture) {
3135 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3136 // to move before deciding what to do.
3137 //
3138 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3139 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3140 // just a press or long-press at the pointer location.
3141 //
3142 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3143 // pointer location.
3144 //
3145 // When the two fingers move enough or when additional fingers are added, we make a decision to
3146 // transition into SWIPE or FREEFORM mode accordingly.
3147 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3148 ALOG_ASSERT(activeTouchId >= 0);
3149
3150 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3151 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3152 bool settled =
3153 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3154 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3155 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3156 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3157 *finishPreviousGesture = true;
3158 } else if (!settled && currentFingerCount > lastFingerCount) {
3159 // Additional pointers have gone down but not yet settled.
3160 // Reset the gesture.
3161 ALOGD_IF(DEBUG_GESTURES,
3162 "Gestures: Resetting gesture since additional pointers went down for "
3163 "MULTITOUCH, settle time remaining %0.3fms",
3164 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3165 when) * 0.000001f);
3166 *cancelPreviousGesture = true;
3167 } else {
3168 // Continue previous gesture.
3169 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3170 }
3171
3172 if (*finishPreviousGesture || *cancelPreviousGesture) {
3173 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3174 mPointerGesture.activeGestureId = 0;
3175 mPointerGesture.referenceIdBits.clear();
3176 mPointerVelocityControl.reset();
3177
3178 // Use the centroid and pointer location as the reference points for the gesture.
3179 ALOGD_IF(DEBUG_GESTURES,
3180 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3181 "%0.3fms",
3182 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3183 when) * 0.000001f);
3184 mCurrentRawState.rawPointerData
3185 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3186 &mPointerGesture.referenceTouchY);
3187 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3188 &mPointerGesture.referenceGestureY);
3189 }
3190
3191 // Clear the reference deltas for fingers not yet included in the reference calculation.
3192 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3193 ~mPointerGesture.referenceIdBits.value);
3194 !idBits.isEmpty();) {
3195 uint32_t id = idBits.clearFirstMarkedBit();
3196 mPointerGesture.referenceDeltas[id].dx = 0;
3197 mPointerGesture.referenceDeltas[id].dy = 0;
3198 }
3199 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3200
3201 // Add delta for all fingers and calculate a common movement delta.
3202 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3203 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3204 mCurrentCookedState.fingerIdBits.value);
3205 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3206 bool first = (idBits == commonIdBits);
3207 uint32_t id = idBits.clearFirstMarkedBit();
3208 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3209 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3210 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3211 delta.dx += cpd.x - lpd.x;
3212 delta.dy += cpd.y - lpd.y;
3213
3214 if (first) {
3215 commonDeltaRawX = delta.dx;
3216 commonDeltaRawY = delta.dy;
3217 } else {
3218 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3219 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3220 }
3221 }
3222
3223 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3224 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3225 float dist[MAX_POINTER_ID + 1];
3226 int32_t distOverThreshold = 0;
3227 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3228 uint32_t id = idBits.clearFirstMarkedBit();
3229 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3230 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3231 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3232 distOverThreshold += 1;
3233 }
3234 }
3235
3236 // Only transition when at least two pointers have moved further than
3237 // the minimum distance threshold.
3238 if (distOverThreshold >= 2) {
3239 if (currentFingerCount > 2) {
3240 // There are more than two pointers, switch to FREEFORM.
3241 ALOGD_IF(DEBUG_GESTURES,
3242 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3243 currentFingerCount);
3244 *cancelPreviousGesture = true;
3245 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3246 } else {
3247 // There are exactly two pointers.
3248 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3249 uint32_t id1 = idBits.clearFirstMarkedBit();
3250 uint32_t id2 = idBits.firstMarkedBit();
3251 const RawPointerData::Pointer& p1 =
3252 mCurrentRawState.rawPointerData.pointerForId(id1);
3253 const RawPointerData::Pointer& p2 =
3254 mCurrentRawState.rawPointerData.pointerForId(id2);
3255 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3256 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3257 // There are two pointers but they are too far apart for a SWIPE,
3258 // switch to FREEFORM.
3259 ALOGD_IF(DEBUG_GESTURES,
3260 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3261 mutualDistance, mPointerGestureMaxSwipeWidth);
3262 *cancelPreviousGesture = true;
3263 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3264 } else {
3265 // There are two pointers. Wait for both pointers to start moving
3266 // before deciding whether this is a SWIPE or FREEFORM gesture.
3267 float dist1 = dist[id1];
3268 float dist2 = dist[id2];
3269 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3270 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3271 // Calculate the dot product of the displacement vectors.
3272 // When the vectors are oriented in approximately the same direction,
3273 // the angle betweeen them is near zero and the cosine of the angle
3274 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3275 // mag(v2).
3276 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3277 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3278 float dx1 = delta1.dx * mPointerXZoomScale;
3279 float dy1 = delta1.dy * mPointerYZoomScale;
3280 float dx2 = delta2.dx * mPointerXZoomScale;
3281 float dy2 = delta2.dy * mPointerYZoomScale;
3282 float dot = dx1 * dx2 + dy1 * dy2;
3283 float cosine = dot / (dist1 * dist2); // denominator always > 0
3284 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3285 // Pointers are moving in the same direction. Switch to SWIPE.
3286 ALOGD_IF(DEBUG_GESTURES,
3287 "Gestures: PRESS transitioned to SWIPE, "
3288 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3289 "cosine %0.3f >= %0.3f",
3290 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3291 mConfig.pointerGestureMultitouchMinDistance, cosine,
3292 mConfig.pointerGestureSwipeTransitionAngleCosine);
3293 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3294 } else {
3295 // Pointers are moving in different directions. Switch to FREEFORM.
3296 ALOGD_IF(DEBUG_GESTURES,
3297 "Gestures: PRESS transitioned to FREEFORM, "
3298 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3299 "cosine %0.3f < %0.3f",
3300 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3301 mConfig.pointerGestureMultitouchMinDistance, cosine,
3302 mConfig.pointerGestureSwipeTransitionAngleCosine);
3303 *cancelPreviousGesture = true;
3304 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3305 }
3306 }
3307 }
3308 }
3309 }
3310 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3311 // Switch from SWIPE to FREEFORM if additional pointers go down.
3312 // Cancel previous gesture.
3313 if (currentFingerCount > 2) {
3314 ALOGD_IF(DEBUG_GESTURES,
3315 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3316 currentFingerCount);
3317 *cancelPreviousGesture = true;
3318 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3319 }
3320 }
3321
3322 // Move the reference points based on the overall group motion of the fingers
3323 // except in PRESS mode while waiting for a transition to occur.
3324 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3325 (commonDeltaRawX || commonDeltaRawY)) {
3326 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3327 uint32_t id = idBits.clearFirstMarkedBit();
3328 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3329 delta.dx = 0;
3330 delta.dy = 0;
3331 }
3332
3333 mPointerGesture.referenceTouchX += commonDeltaRawX;
3334 mPointerGesture.referenceTouchY += commonDeltaRawY;
3335
3336 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3337 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3338
3339 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3340 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3341
3342 mPointerGesture.referenceGestureX += commonDeltaX;
3343 mPointerGesture.referenceGestureY += commonDeltaY;
3344 }
3345
3346 // Report gestures.
3347 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3348 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3349 // PRESS or SWIPE mode.
3350 ALOGD_IF(DEBUG_GESTURES,
3351 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3352 "currentTouchPointerCount=%d",
3353 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3354 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3355
3356 mPointerGesture.currentGestureIdBits.clear();
3357 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3358 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3359 mPointerGesture.currentGestureProperties[0].clear();
3360 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3361 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3362 mPointerGesture.currentGestureCoords[0].clear();
3363 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3364 mPointerGesture.referenceGestureX);
3365 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3366 mPointerGesture.referenceGestureY);
3367 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3368 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3369 float xOffset = static_cast<float>(commonDeltaRawX) /
3370 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3371 float yOffset = static_cast<float>(commonDeltaRawY) /
3372 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3373 mPointerGesture.currentGestureCoords[0]
3374 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3375 mPointerGesture.currentGestureCoords[0]
3376 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3377 }
3378 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3379 // FREEFORM mode.
3380 ALOGD_IF(DEBUG_GESTURES,
3381 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3382 "currentTouchPointerCount=%d",
3383 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3384 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3385
3386 mPointerGesture.currentGestureIdBits.clear();
3387
3388 BitSet32 mappedTouchIdBits;
3389 BitSet32 usedGestureIdBits;
3390 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3391 // Initially, assign the active gesture id to the active touch point
3392 // if there is one. No other touch id bits are mapped yet.
3393 if (!*cancelPreviousGesture) {
3394 mappedTouchIdBits.markBit(activeTouchId);
3395 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3396 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3397 mPointerGesture.activeGestureId;
3398 } else {
3399 mPointerGesture.activeGestureId = -1;
3400 }
3401 } else {
3402 // Otherwise, assume we mapped all touches from the previous frame.
3403 // Reuse all mappings that are still applicable.
3404 mappedTouchIdBits.value =
3405 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3406 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3407
3408 // Check whether we need to choose a new active gesture id because the
3409 // current went went up.
3410 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3411 ~mCurrentCookedState.fingerIdBits.value);
3412 !upTouchIdBits.isEmpty();) {
3413 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3414 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3415 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3416 mPointerGesture.activeGestureId = -1;
3417 break;
3418 }
3419 }
3420 }
3421
3422 ALOGD_IF(DEBUG_GESTURES,
3423 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3424 "activeGestureId=%d",
3425 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3426
3427 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3428 for (uint32_t i = 0; i < currentFingerCount; i++) {
3429 uint32_t touchId = idBits.clearFirstMarkedBit();
3430 uint32_t gestureId;
3431 if (!mappedTouchIdBits.hasBit(touchId)) {
3432 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3433 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3434 ALOGD_IF(DEBUG_GESTURES,
3435 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3436 gestureId);
3437 } else {
3438 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3439 ALOGD_IF(DEBUG_GESTURES,
3440 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3441 touchId, gestureId);
3442 }
3443 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3444 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3445
3446 const RawPointerData::Pointer& pointer =
3447 mCurrentRawState.rawPointerData.pointerForId(touchId);
3448 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3449 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3450 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3451
3452 mPointerGesture.currentGestureProperties[i].clear();
3453 mPointerGesture.currentGestureProperties[i].id = gestureId;
3454 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3455 mPointerGesture.currentGestureCoords[i].clear();
3456 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3457 mPointerGesture.referenceGestureX +
3458 deltaX);
3459 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3460 mPointerGesture.referenceGestureY +
3461 deltaY);
3462 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3463 }
3464
3465 if (mPointerGesture.activeGestureId < 0) {
3466 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3467 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3468 mPointerGesture.activeGestureId);
3469 }
3470 }
3471}
3472
Harry Cutts714d1ad2022-08-24 16:36:43 +00003473void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3474 const RawPointerData::Pointer& currentPointer =
3475 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3476 const RawPointerData::Pointer& lastPointer =
3477 mLastRawState.rawPointerData.pointerForId(pointerId);
3478 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3479 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3480
3481 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3482 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3483
3484 mPointerController->move(deltaX, deltaY);
3485}
3486
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003487std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3488 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489 mPointerSimple.currentCoords.clear();
3490 mPointerSimple.currentProperties.clear();
3491
3492 bool down, hovering;
3493 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3494 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3495 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003496 mPointerController
3497 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3498 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003499
3500 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3501 down = !hovering;
3502
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003503 float x, y;
3504 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003505 mPointerSimple.currentCoords.copyFrom(
3506 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3507 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3508 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3509 mPointerSimple.currentProperties.id = 0;
3510 mPointerSimple.currentProperties.toolType =
3511 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3512 } else {
3513 down = false;
3514 hovering = false;
3515 }
3516
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003517 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003518}
3519
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003520std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3521 uint32_t policyFlags) {
3522 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003523}
3524
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003525std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3526 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527 mPointerSimple.currentCoords.clear();
3528 mPointerSimple.currentProperties.clear();
3529
3530 bool down, hovering;
3531 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3532 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003533 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003534 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003535 } else {
3536 mPointerVelocityControl.reset();
3537 }
3538
3539 down = isPointerDown(mCurrentRawState.buttonState);
3540 hovering = !down;
3541
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003542 float x, y;
3543 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003544 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003545 mPointerSimple.currentCoords.copyFrom(
3546 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3547 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3548 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3549 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3550 hovering ? 0.0f : 1.0f);
3551 mPointerSimple.currentProperties.id = 0;
3552 mPointerSimple.currentProperties.toolType =
3553 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3554 } else {
3555 mPointerVelocityControl.reset();
3556
3557 down = false;
3558 hovering = false;
3559 }
3560
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003561 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003562}
3563
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003564std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3565 uint32_t policyFlags) {
3566 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567
3568 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003569
3570 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571}
3572
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003573std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3574 uint32_t policyFlags, bool down,
3575 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003576 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3577 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003578 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003579 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003580
3581 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003582 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003583 mPointerController->clearSpots();
3584 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003585 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003586 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003587 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003588 }
Garfield Tan9514d782020-11-10 16:37:23 -08003589 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003591 float xCursorPosition, yCursorPosition;
3592 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593
3594 if (mPointerSimple.down && !down) {
3595 mPointerSimple.down = false;
3596
3597 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003598 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3599 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3600 0, metaState, mLastRawState.buttonState,
3601 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3602 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3603 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3604 yCursorPosition, mPointerSimple.downTime,
3605 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606 }
3607
3608 if (mPointerSimple.hovering && !hovering) {
3609 mPointerSimple.hovering = false;
3610
3611 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003612 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3613 mSource, displayId, policyFlags,
3614 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3615 mLastRawState.buttonState, MotionClassification::NONE,
3616 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3617 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3618 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3619 yCursorPosition, mPointerSimple.downTime,
3620 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003621 }
3622
3623 if (down) {
3624 if (!mPointerSimple.down) {
3625 mPointerSimple.down = true;
3626 mPointerSimple.downTime = when;
3627
3628 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003629 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3630 mSource, displayId, policyFlags,
3631 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3632 mCurrentRawState.buttonState, MotionClassification::NONE,
3633 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3634 &mPointerSimple.currentProperties,
3635 &mPointerSimple.currentCoords, mOrientedXPrecision,
3636 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3637 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003638 }
3639
3640 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003641 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3642 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3643 0, 0, metaState, mCurrentRawState.buttonState,
3644 MotionClassification::NONE, 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 if (hovering) {
3652 if (!mPointerSimple.hovering) {
3653 mPointerSimple.hovering = true;
3654
3655 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003656 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3657 mSource, displayId, policyFlags,
3658 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3659 mCurrentRawState.buttonState, MotionClassification::NONE,
3660 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3661 &mPointerSimple.currentProperties,
3662 &mPointerSimple.currentCoords, mOrientedXPrecision,
3663 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3664 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003665 }
3666
3667 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003668 out.push_back(
3669 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3670 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3671 metaState, mCurrentRawState.buttonState,
3672 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3673 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3674 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3675 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003676 }
3677
3678 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3679 float vscroll = mCurrentRawState.rawVScroll;
3680 float hscroll = mCurrentRawState.rawHScroll;
3681 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3682 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3683
3684 // Send scroll.
3685 PointerCoords pointerCoords;
3686 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3687 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3688 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3689
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003690 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3691 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3692 0, 0, metaState, mCurrentRawState.buttonState,
3693 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3694 &mPointerSimple.currentProperties, &pointerCoords,
3695 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3696 yCursorPosition, mPointerSimple.downTime,
3697 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003698 }
3699
3700 // Save state.
3701 if (down || hovering) {
3702 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3703 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003704 mPointerSimple.displayId = displayId;
3705 mPointerSimple.source = mSource;
3706 mPointerSimple.lastCursorX = xCursorPosition;
3707 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003708 } else {
3709 mPointerSimple.reset();
3710 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003711 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003712}
3713
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003714std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3715 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003716 std::list<NotifyArgs> out;
3717 if (mPointerSimple.down || mPointerSimple.hovering) {
3718 int32_t metaState = getContext()->getGlobalMetaState();
3719 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3720 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3721 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3722 metaState, mLastRawState.buttonState,
3723 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3724 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3725 mOrientedXPrecision, mOrientedYPrecision,
3726 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3727 mPointerSimple.downTime,
3728 /* videoFrames */ {}));
3729 if (mPointerController != nullptr) {
3730 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3731 }
3732 }
3733 mPointerSimple.reset();
3734 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003735}
3736
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003737NotifyMotionArgs TouchInputMapper::dispatchMotion(
3738 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3739 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003740 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3741 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003742 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003743 PointerCoords pointerCoords[MAX_POINTERS];
3744 PointerProperties pointerProperties[MAX_POINTERS];
3745 uint32_t pointerCount = 0;
3746 while (!idBits.isEmpty()) {
3747 uint32_t id = idBits.clearFirstMarkedBit();
3748 uint32_t index = idToIndex[id];
3749 pointerProperties[pointerCount].copyFrom(properties[index]);
3750 pointerCoords[pointerCount].copyFrom(coords[index]);
3751
3752 if (changedId >= 0 && id == uint32_t(changedId)) {
3753 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3754 }
3755
3756 pointerCount += 1;
3757 }
3758
3759 ALOG_ASSERT(pointerCount != 0);
3760
3761 if (changedId >= 0 && pointerCount == 1) {
3762 // Replace initial down and final up action.
3763 // We can compare the action without masking off the changed pointer index
3764 // because we know the index is 0.
3765 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3766 action = AMOTION_EVENT_ACTION_DOWN;
3767 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003768 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3769 action = AMOTION_EVENT_ACTION_CANCEL;
3770 } else {
3771 action = AMOTION_EVENT_ACTION_UP;
3772 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003773 } else {
3774 // Can't happen.
3775 ALOG_ASSERT(false);
3776 }
3777 }
3778 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3779 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003780 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003781 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003782 }
3783 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3784 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003785 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003786 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003787 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003788 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3789 policyFlags, action, actionButton, flags, metaState, buttonState,
3790 classification, edgeFlags, pointerCount, pointerProperties,
3791 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3792 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003793}
3794
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003795std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3796 std::list<NotifyArgs> out;
3797 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3798 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3799 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003800}
3801
Prabir Pradhan1728b212021-10-19 16:00:03 -07003802// Transform input device coordinates to display panel coordinates.
3803void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003804 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3805 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3806
arthurhunga36b28e2020-12-29 20:28:15 +08003807 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3808 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3809
Prabir Pradhan1728b212021-10-19 16:00:03 -07003810 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003811 // 0 - no swap and reverse.
3812 // 90 - swap x/y and reverse y.
3813 // 180 - reverse x, y.
3814 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003815 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003816 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003817 x = xScaled;
3818 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003819 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003820 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003821 y = xScaledMax;
3822 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003823 break;
3824 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003825 x = xScaledMax;
3826 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003827 break;
3828 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003829 y = xScaled;
3830 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003831 break;
3832 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003833 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003834 }
3835}
3836
Prabir Pradhan1728b212021-10-19 16:00:03 -07003837bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003838 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3839 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3840
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003841 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003842 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003843 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003844 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003845}
3846
3847const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3848 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003849 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3850 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3851 "left=%d, top=%d, right=%d, bottom=%d",
3852 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3853 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003854
3855 if (virtualKey.isHit(x, y)) {
3856 return &virtualKey;
3857 }
3858 }
3859
3860 return nullptr;
3861}
3862
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003863void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3864 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3865 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003866
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003867 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003868
3869 if (currentPointerCount == 0) {
3870 // No pointers to assign.
3871 return;
3872 }
3873
3874 if (lastPointerCount == 0) {
3875 // All pointers are new.
3876 for (uint32_t i = 0; i < currentPointerCount; i++) {
3877 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003878 current.rawPointerData.pointers[i].id = id;
3879 current.rawPointerData.idToIndex[id] = i;
3880 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003881 }
3882 return;
3883 }
3884
3885 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003886 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003887 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003888 uint32_t id = last.rawPointerData.pointers[0].id;
3889 current.rawPointerData.pointers[0].id = id;
3890 current.rawPointerData.idToIndex[id] = 0;
3891 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003892 return;
3893 }
3894
3895 // General case.
3896 // We build a heap of squared euclidean distances between current and last pointers
3897 // associated with the current and last pointer indices. Then, we find the best
3898 // match (by distance) for each current pointer.
3899 // The pointers must have the same tool type but it is possible for them to
3900 // transition from hovering to touching or vice-versa while retaining the same id.
3901 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3902
3903 uint32_t heapSize = 0;
3904 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3905 currentPointerIndex++) {
3906 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3907 lastPointerIndex++) {
3908 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003909 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003910 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003911 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003912 if (currentPointer.toolType == lastPointer.toolType) {
3913 int64_t deltaX = currentPointer.x - lastPointer.x;
3914 int64_t deltaY = currentPointer.y - lastPointer.y;
3915
3916 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3917
3918 // Insert new element into the heap (sift up).
3919 heap[heapSize].currentPointerIndex = currentPointerIndex;
3920 heap[heapSize].lastPointerIndex = lastPointerIndex;
3921 heap[heapSize].distance = distance;
3922 heapSize += 1;
3923 }
3924 }
3925 }
3926
3927 // Heapify
3928 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3929 startIndex -= 1;
3930 for (uint32_t parentIndex = startIndex;;) {
3931 uint32_t childIndex = parentIndex * 2 + 1;
3932 if (childIndex >= heapSize) {
3933 break;
3934 }
3935
3936 if (childIndex + 1 < heapSize &&
3937 heap[childIndex + 1].distance < heap[childIndex].distance) {
3938 childIndex += 1;
3939 }
3940
3941 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3942 break;
3943 }
3944
3945 swap(heap[parentIndex], heap[childIndex]);
3946 parentIndex = childIndex;
3947 }
3948 }
3949
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003950 if (DEBUG_POINTER_ASSIGNMENT) {
3951 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3952 for (size_t i = 0; i < heapSize; i++) {
3953 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3954 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3955 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003956 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003957
3958 // Pull matches out by increasing order of distance.
3959 // To avoid reassigning pointers that have already been matched, the loop keeps track
3960 // of which last and current pointers have been matched using the matchedXXXBits variables.
3961 // It also tracks the used pointer id bits.
3962 BitSet32 matchedLastBits(0);
3963 BitSet32 matchedCurrentBits(0);
3964 BitSet32 usedIdBits(0);
3965 bool first = true;
3966 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3967 while (heapSize > 0) {
3968 if (first) {
3969 // The first time through the loop, we just consume the root element of
3970 // the heap (the one with smallest distance).
3971 first = false;
3972 } else {
3973 // Previous iterations consumed the root element of the heap.
3974 // Pop root element off of the heap (sift down).
3975 heap[0] = heap[heapSize];
3976 for (uint32_t parentIndex = 0;;) {
3977 uint32_t childIndex = parentIndex * 2 + 1;
3978 if (childIndex >= heapSize) {
3979 break;
3980 }
3981
3982 if (childIndex + 1 < heapSize &&
3983 heap[childIndex + 1].distance < heap[childIndex].distance) {
3984 childIndex += 1;
3985 }
3986
3987 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3988 break;
3989 }
3990
3991 swap(heap[parentIndex], heap[childIndex]);
3992 parentIndex = childIndex;
3993 }
3994
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003995 if (DEBUG_POINTER_ASSIGNMENT) {
3996 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3997 for (size_t j = 0; j < heapSize; j++) {
3998 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3999 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4000 heap[j].distance);
4001 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004002 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004003 }
4004
4005 heapSize -= 1;
4006
4007 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4008 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4009
4010 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4011 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4012
4013 matchedCurrentBits.markBit(currentPointerIndex);
4014 matchedLastBits.markBit(lastPointerIndex);
4015
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004016 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4017 current.rawPointerData.pointers[currentPointerIndex].id = id;
4018 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4019 current.rawPointerData.markIdBit(id,
4020 current.rawPointerData.isHovering(
4021 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004022 usedIdBits.markBit(id);
4023
Harry Cutts45483602022-08-24 14:36:48 +00004024 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4025 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4026 ", distance=%" PRIu64,
4027 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004028 break;
4029 }
4030 }
4031
4032 // Assign fresh ids to pointers that were not matched in the process.
4033 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4034 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4035 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4036
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004037 current.rawPointerData.pointers[currentPointerIndex].id = id;
4038 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4039 current.rawPointerData.markIdBit(id,
4040 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004041
Harry Cutts45483602022-08-24 14:36:48 +00004042 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4043 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4044 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004045 }
4046}
4047
4048int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4049 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4050 return AKEY_STATE_VIRTUAL;
4051 }
4052
4053 for (const VirtualKey& virtualKey : mVirtualKeys) {
4054 if (virtualKey.keyCode == keyCode) {
4055 return AKEY_STATE_UP;
4056 }
4057 }
4058
4059 return AKEY_STATE_UNKNOWN;
4060}
4061
4062int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4063 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4064 return AKEY_STATE_VIRTUAL;
4065 }
4066
4067 for (const VirtualKey& virtualKey : mVirtualKeys) {
4068 if (virtualKey.scanCode == scanCode) {
4069 return AKEY_STATE_UP;
4070 }
4071 }
4072
4073 return AKEY_STATE_UNKNOWN;
4074}
4075
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004076bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4077 const std::vector<int32_t>& keyCodes,
4078 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004079 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004080 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004081 if (virtualKey.keyCode == keyCodes[i]) {
4082 outFlags[i] = 1;
4083 }
4084 }
4085 }
4086
4087 return true;
4088}
4089
4090std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4091 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004092 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004093 return std::make_optional(mPointerController->getDisplayId());
4094 } else {
4095 return std::make_optional(mViewport.displayId);
4096 }
4097 }
4098 return std::nullopt;
4099}
4100
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004101} // namespace android