blob: de1ed0149520143ea24173df7c85e4cbca3c02c8 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000024#include <input/PrintTools.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070026#include "CursorButtonAccumulator.h"
27#include "CursorScrollAccumulator.h"
28#include "TouchButtonAccumulator.h"
29#include "TouchCursorInputMapperCommon.h"
30
31namespace android {
32
33// --- Constants ---
34
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070035// Artificial latency on synthetic events created from stylus data without corresponding touch
36// data.
37static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
38
HQ Liue6983c72022-04-19 22:14:56 +000039// Minimum width between two pointers to determine a gesture as freeform gesture in mm
40static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070041// --- Static Definitions ---
42
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000043static const DisplayViewport kUninitializedViewport;
44
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000045static std::string toString(const Rect& rect) {
46 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
47}
48
49static std::string toString(const ui::Size& size) {
50 return base::StringPrintf("%dx%d", size.width, size.height);
51}
52
53static bool isPointInRect(const Rect& rect, int32_t x, int32_t y) {
54 // Consider all four sides as "inclusive".
55 return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
56}
57
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070058template <typename T>
59inline static void swap(T& a, T& b) {
60 T temp = a;
61 a = b;
62 b = temp;
63}
64
65static float calculateCommonVector(float a, float b) {
66 if (a > 0 && b > 0) {
67 return a < b ? a : b;
68 } else if (a < 0 && b < 0) {
69 return a > b ? a : b;
70 } else {
71 return 0;
72 }
73}
74
75inline static float distance(float x1, float y1, float x2, float y2) {
76 return hypotf(x1 - x2, y1 - y2);
77}
78
79inline static int32_t signExtendNybble(int32_t value) {
80 return value >= 8 ? value - 16 : value;
81}
82
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070083// --- RawPointerData ---
84
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070085void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
86 float x = 0, y = 0;
87 uint32_t count = touchingIdBits.count();
88 if (count) {
89 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
90 uint32_t id = idBits.clearFirstMarkedBit();
91 const Pointer& pointer = pointerForId(id);
92 x += pointer.x;
93 y += pointer.y;
94 }
95 x /= count;
96 y /= count;
97 }
98 *outX = x;
99 *outY = y;
100}
101
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700102// --- TouchInputMapper ---
103
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800104TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
105 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000106 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700107 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100108 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700109 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700110
111TouchInputMapper::~TouchInputMapper() {}
112
Philip Junker4af3b3d2021-12-14 10:36:55 +0100113uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700114 return mSource;
115}
116
117void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
118 InputMapper::populateDeviceInfo(info);
119
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000120 if (mDeviceMode == DeviceMode::DISABLED) {
121 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700122 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000123
124 info->addMotionRange(mOrientedRanges.x);
125 info->addMotionRange(mOrientedRanges.y);
126 info->addMotionRange(mOrientedRanges.pressure);
127
128 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
129 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
130 //
131 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
132 // motion, i.e. the hardware dimensions, as the finger could move completely across the
133 // touchpad in one sample cycle.
134 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
135 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
136 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
137 x.resolution);
138 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
139 y.resolution);
140 }
141
142 if (mOrientedRanges.size) {
143 info->addMotionRange(*mOrientedRanges.size);
144 }
145
146 if (mOrientedRanges.touchMajor) {
147 info->addMotionRange(*mOrientedRanges.touchMajor);
148 info->addMotionRange(*mOrientedRanges.touchMinor);
149 }
150
151 if (mOrientedRanges.toolMajor) {
152 info->addMotionRange(*mOrientedRanges.toolMajor);
153 info->addMotionRange(*mOrientedRanges.toolMinor);
154 }
155
156 if (mOrientedRanges.orientation) {
157 info->addMotionRange(*mOrientedRanges.orientation);
158 }
159
160 if (mOrientedRanges.distance) {
161 info->addMotionRange(*mOrientedRanges.distance);
162 }
163
164 if (mOrientedRanges.tilt) {
165 info->addMotionRange(*mOrientedRanges.tilt);
166 }
167
168 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
169 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
170 }
171 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
172 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
173 }
174 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
175 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
176 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
177 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
178 x.resolution);
179 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
180 y.resolution);
181 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
182 x.resolution);
183 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
184 y.resolution);
185 }
186 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000187 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700188}
189
190void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700191 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800192 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700193 dumpParameters(dump);
194 dumpVirtualKeys(dump);
195 dumpRawPointerAxes(dump);
196 dumpCalibration(dump);
197 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700198 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700199
200 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700201 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
202 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
203 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
204 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
205 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
206 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
207 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
208 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
209 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
210 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
211 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
212 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
213 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
214 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
215
216 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
217 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
218 mLastRawState.rawPointerData.pointerCount);
219 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
220 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
221 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
222 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
223 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
224 "toolType=%d, isHovering=%s\n",
225 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
226 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
227 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
228 pointer.distance, pointer.toolType, toString(pointer.isHovering));
229 }
230
231 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
232 mLastCookedState.buttonState);
233 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
234 mLastCookedState.cookedPointerData.pointerCount);
235 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
236 const PointerProperties& pointerProperties =
237 mLastCookedState.cookedPointerData.pointerProperties[i];
238 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000239 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
240 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
241 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700242 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
243 "toolType=%d, isHovering=%s\n",
244 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000245 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
246 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700247 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
248 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
249 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
250 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
251 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
252 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
253 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
254 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
255 pointerProperties.toolType,
256 toString(mLastCookedState.cookedPointerData.isHovering(i)));
257 }
258
259 dump += INDENT3 "Stylus Fusion:\n";
260 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
261 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000262 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
263 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700264 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
265 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000266 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
267 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700268 dump += INDENT3 "External Stylus State:\n";
269 dumpStylusState(dump, mExternalStylusState);
270
Michael Wright227c5542020-07-02 18:30:52 +0100271 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700272 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
273 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
274 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
275 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
276 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
277 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
278 }
279}
280
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700281std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
282 const InputReaderConfiguration* config,
283 uint32_t changes) {
284 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700285
286 mConfig = *config;
287
288 if (!changes) { // first time only
289 // Configure basic parameters.
290 configureParameters();
291
292 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800293 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000294 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700295
296 // Configure absolute axis information.
297 configureRawPointerAxes();
298
299 // Prepare input device calibration.
300 parseCalibration();
301 resolveCalibration();
302 }
303
304 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
305 // Update location calibration to reflect current settings
306 updateAffineTransformation();
307 }
308
309 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
310 // Update pointer speed.
311 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
312 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
313 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
314 }
315
316 bool resetNeeded = false;
317 if (!changes ||
318 (changes &
319 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800320 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700321 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
322 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
323 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700324 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700325 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700326 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700327 }
328
329 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700330 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000331
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700332 // Send reset, unless this is the first time the device has been configured,
333 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000334 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700335 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700336 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337}
338
339void TouchInputMapper::resolveExternalStylusPresence() {
340 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800341 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700342 mExternalStylusConnected = !devices.empty();
343
344 if (!mExternalStylusConnected) {
345 resetExternalStylus();
346 }
347}
348
349void TouchInputMapper::configureParameters() {
350 // Use the pointer presentation mode for devices that do not support distinct
351 // multitouch. The spot-based presentation relies on being able to accurately
352 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800353 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100354 ? Parameters::GestureMode::SINGLE_TOUCH
355 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700356
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700357 std::string gestureModeString;
358 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800359 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700360 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100361 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700362 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100363 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700365 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700366 }
367 }
368
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800369 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700370 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100371 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800372 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700373 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100374 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700375 } else {
376 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100377 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700378 }
379
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800380 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700381
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700382 std::string deviceTypeString;
383 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800384 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700385 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100386 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700387 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100388 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100390 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700391 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700392 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700393 }
394 }
395
Michael Wright227c5542020-07-02 18:30:52 +0100396 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700397 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800398 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700399
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700400 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700401 std::string orientationString;
402 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700403 orientationString)) {
404 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
405 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
406 } else if (orientationString == "ORIENTATION_90") {
407 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
408 } else if (orientationString == "ORIENTATION_180") {
409 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
410 } else if (orientationString == "ORIENTATION_270") {
411 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
412 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700413 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700414 }
415 }
416
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700417 mParameters.hasAssociatedDisplay = false;
418 mParameters.associatedDisplayIsExternal = false;
419 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100420 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
421 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100423 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800424 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700425 std::string uniqueDisplayId;
426 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800427 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
429 }
430 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800431 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700432 mParameters.hasAssociatedDisplay = true;
433 }
434
435 // Initial downs on external touch devices should wake the device.
436 // Normally we don't do this for internal touch screens to prevent them from waking
437 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800438 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700439 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000440
441 mParameters.supportsUsi = false;
442 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
443 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700444
445 mParameters.enableForInactiveViewport = false;
446 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
447 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448}
449
450void TouchInputMapper::dumpParameters(std::string& dump) {
451 dump += INDENT3 "Parameters:\n";
452
Dominik Laskowski75788452021-02-09 18:51:25 -0800453 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700454
Dominik Laskowski75788452021-02-09 18:51:25 -0800455 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456
457 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
458 "displayId='%s'\n",
459 toString(mParameters.hasAssociatedDisplay),
460 toString(mParameters.associatedDisplayIsExternal),
461 mParameters.uniqueDisplayId.c_str());
462 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800463 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000464 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700465 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
466 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700467}
468
469void TouchInputMapper::configureRawPointerAxes() {
470 mRawPointerAxes.clear();
471}
472
473void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
474 dump += INDENT3 "Raw Touch Axes:\n";
475 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
476 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
477 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
478 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
479 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
480 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
481 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
482 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
483 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
484 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
485 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
486 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
487 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
488}
489
490bool TouchInputMapper::hasExternalStylus() const {
491 return mExternalStylusConnected;
492}
493
494/**
495 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000496 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800497 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000498 * 3. Get the matching viewport by either unique id in idc file or by the display type
499 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800500 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700501 */
502std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800503 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000504 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800505 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700506 }
507
Christine Franks2a2293c2022-01-18 11:51:16 -0800508 const std::optional<std::string> associatedDisplayUniqueId =
509 getDeviceContext().getAssociatedDisplayUniqueId();
510 if (associatedDisplayUniqueId) {
511 return getDeviceContext().getAssociatedViewport();
512 }
513
Michael Wright227c5542020-07-02 18:30:52 +0100514 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800515 std::optional<DisplayViewport> viewport =
516 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
517 if (viewport) {
518 return viewport;
519 } else {
520 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
521 mConfig.defaultPointerDisplayId);
522 }
523 }
524
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700525 // Check if uniqueDisplayId is specified in idc file.
526 if (!mParameters.uniqueDisplayId.empty()) {
527 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
528 }
529
530 ViewportType viewportTypeToUse;
531 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100532 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700533 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100534 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700535 }
536
537 std::optional<DisplayViewport> viewport =
538 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100539 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700540 ALOGW("Input device %s should be associated with external display, "
541 "fallback to internal one for the external viewport is not found.",
542 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100543 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700544 }
545
546 return viewport;
547 }
548
549 // No associated display, return a non-display viewport.
550 DisplayViewport newViewport;
551 // Raw width and height in the natural orientation.
552 int32_t rawWidth = mRawPointerAxes.getRawWidth();
553 int32_t rawHeight = mRawPointerAxes.getRawHeight();
554 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
555 return std::make_optional(newViewport);
556}
557
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800558int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
559 if (resolution < 0) {
560 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
561 getDeviceName().c_str());
562 return 0;
563 }
564 return resolution;
565}
566
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800567void TouchInputMapper::initializeSizeRanges() {
568 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
569 mSizeScale = 0.0f;
570 return;
571 }
572
573 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000574 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800575
576 // Size factors.
577 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
578 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
579 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
580 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
581 } else {
582 mSizeScale = 0.0f;
583 }
584
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700585 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
586 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
587 .source = mSource,
588 .min = 0,
589 .max = diagonalSize,
590 .flat = 0,
591 .fuzz = 0,
592 .resolution = 0,
593 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800594
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800595 if (mRawPointerAxes.touchMajor.valid) {
596 mRawPointerAxes.touchMajor.resolution =
597 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700598 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800599 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800600
601 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700602 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800603 if (mRawPointerAxes.touchMinor.valid) {
604 mRawPointerAxes.touchMinor.resolution =
605 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700606 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800607 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800608
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700609 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
610 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
611 .source = mSource,
612 .min = 0,
613 .max = diagonalSize,
614 .flat = 0,
615 .fuzz = 0,
616 .resolution = 0,
617 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800618 if (mRawPointerAxes.toolMajor.valid) {
619 mRawPointerAxes.toolMajor.resolution =
620 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700621 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800622 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800623
624 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700625 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800626 if (mRawPointerAxes.toolMinor.valid) {
627 mRawPointerAxes.toolMinor.resolution =
628 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700629 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800630 }
631
632 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700633 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
634 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
635 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
636 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800637 } else {
638 // Support for other calibrations can be added here.
639 ALOGW("%s calibration is not supported for size ranges at the moment. "
640 "Using raw resolution instead",
641 ftl::enum_string(mCalibration.sizeCalibration).c_str());
642 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800643
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700644 mOrientedRanges.size = InputDeviceInfo::MotionRange{
645 .axis = AMOTION_EVENT_AXIS_SIZE,
646 .source = mSource,
647 .min = 0,
648 .max = 1.0,
649 .flat = 0,
650 .fuzz = 0,
651 .resolution = 0,
652 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800653}
654
655void TouchInputMapper::initializeOrientedRanges() {
656 // Configure X and Y factors.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000657 mXScale = float(mDisplayBounds.width) / mRawPointerAxes.getRawWidth();
658 mYScale = float(mDisplayBounds.height) / mRawPointerAxes.getRawHeight();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800659 mXPrecision = 1.0f / mXScale;
660 mYPrecision = 1.0f / mYScale;
661
662 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
663 mOrientedRanges.x.source = mSource;
664 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
665 mOrientedRanges.y.source = mSource;
666
667 // Scale factor for terms that are not oriented in a particular axis.
668 // If the pixels are square then xScale == yScale otherwise we fake it
669 // by choosing an average.
670 mGeometricScale = avg(mXScale, mYScale);
671
672 initializeSizeRanges();
673
674 // Pressure factors.
675 mPressureScale = 0;
676 float pressureMax = 1.0;
677 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
678 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700679 if (mCalibration.pressureScale) {
680 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800681 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
682 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
683 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
684 }
685 }
686
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700687 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
688 .axis = AMOTION_EVENT_AXIS_PRESSURE,
689 .source = mSource,
690 .min = 0,
691 .max = pressureMax,
692 .flat = 0,
693 .fuzz = 0,
694 .resolution = 0,
695 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800696
697 // Tilt
698 mTiltXCenter = 0;
699 mTiltXScale = 0;
700 mTiltYCenter = 0;
701 mTiltYScale = 0;
702 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
703 if (mHaveTilt) {
704 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
705 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
706 mTiltXScale = M_PI / 180;
707 mTiltYScale = M_PI / 180;
708
709 if (mRawPointerAxes.tiltX.resolution) {
710 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
711 }
712 if (mRawPointerAxes.tiltY.resolution) {
713 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
714 }
715
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700716 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
717 .axis = AMOTION_EVENT_AXIS_TILT,
718 .source = mSource,
719 .min = 0,
720 .max = M_PI_2,
721 .flat = 0,
722 .fuzz = 0,
723 .resolution = 0,
724 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800725 }
726
727 // Orientation
728 mOrientationScale = 0;
729 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700730 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
731 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
732 .source = mSource,
733 .min = -M_PI,
734 .max = M_PI,
735 .flat = 0,
736 .fuzz = 0,
737 .resolution = 0,
738 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800739
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800740 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
741 if (mCalibration.orientationCalibration ==
742 Calibration::OrientationCalibration::INTERPOLATED) {
743 if (mRawPointerAxes.orientation.valid) {
744 if (mRawPointerAxes.orientation.maxValue > 0) {
745 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
746 } else if (mRawPointerAxes.orientation.minValue < 0) {
747 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
748 } else {
749 mOrientationScale = 0;
750 }
751 }
752 }
753
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700754 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
755 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
756 .source = mSource,
757 .min = -M_PI_2,
758 .max = M_PI_2,
759 .flat = 0,
760 .fuzz = 0,
761 .resolution = 0,
762 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800763 }
764
765 // Distance
766 mDistanceScale = 0;
767 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
768 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700769 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800770 }
771
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700772 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800773
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700774 .axis = AMOTION_EVENT_AXIS_DISTANCE,
775 .source = mSource,
776 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
777 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
778 .flat = 0,
779 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
780 .resolution = 0,
781 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800782 }
783
784 // Compute oriented precision, scales and ranges.
785 // Note that the maximum value reported is an inclusive maximum value so it is one
786 // unit less than the total width or height of the display.
787 switch (mInputDeviceOrientation) {
788 case DISPLAY_ORIENTATION_90:
789 case DISPLAY_ORIENTATION_270:
790 mOrientedXPrecision = mYPrecision;
791 mOrientedYPrecision = mXPrecision;
792
793 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000794 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800795 mOrientedRanges.x.flat = 0;
796 mOrientedRanges.x.fuzz = 0;
797 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
798
799 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000800 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800801 mOrientedRanges.y.flat = 0;
802 mOrientedRanges.y.fuzz = 0;
803 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
804 break;
805
806 default:
807 mOrientedXPrecision = mXPrecision;
808 mOrientedYPrecision = mYPrecision;
809
810 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000811 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800812 mOrientedRanges.x.flat = 0;
813 mOrientedRanges.x.fuzz = 0;
814 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
815
816 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000817 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800818 mOrientedRanges.y.flat = 0;
819 mOrientedRanges.y.fuzz = 0;
820 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
821 break;
822 }
823}
824
Prabir Pradhan1728b212021-10-19 16:00:03 -0700825void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000826 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700827
828 resolveExternalStylusPresence();
829
830 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100831 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000832 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700833 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100834 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700835 if (hasStylus()) {
836 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000837 } else {
838 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700839 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800840 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700841 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100842 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700843 if (hasStylus()) {
844 mSource |= AINPUT_SOURCE_STYLUS;
845 }
846 if (hasExternalStylus()) {
847 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
848 }
Michael Wright227c5542020-07-02 18:30:52 +0100849 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700850 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100851 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700852 } else {
853 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100854 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700855 }
856
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000857 const std::optional<DisplayViewport> newViewportOpt = findViewport();
858
859 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700860 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
861 ALOGW("Touch device '%s' did not report support for X or Y axis! "
862 "The device will be inoperable.",
863 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100864 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000865 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700866 ALOGI("Touch device '%s' could not query the properties of its associated "
867 "display. The device will be inoperable until the display size "
868 "becomes available.",
869 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100870 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700871 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000872 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
873 getDeviceName().c_str(), getDeviceId());
874 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000875 }
876
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700877 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000878 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000879 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
880 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
881 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
882 const float rawMeanResolution =
883 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700884
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000885 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
886 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700887 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700888 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000889 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
890 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
891 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700892
Michael Wright227c5542020-07-02 18:30:52 +0100893 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700894 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700895 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
896 int32_t naturalPhysicalLeft, naturalPhysicalTop;
897 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700898
Prabir Pradhan1728b212021-10-19 16:00:03 -0700899 // Apply the inverse of the input device orientation so that the input device is
900 // configured in the same orientation as the viewport. The input device orientation will
901 // be re-applied by mInputDeviceOrientation.
902 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700903 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700904 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700905 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700906 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
907 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800908 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700909 naturalPhysicalTop = mViewport.physicalLeft;
910 naturalDeviceWidth = mViewport.deviceHeight;
911 naturalDeviceHeight = mViewport.deviceWidth;
912 break;
913 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700914 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
915 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
916 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
917 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
918 naturalDeviceWidth = mViewport.deviceWidth;
919 naturalDeviceHeight = mViewport.deviceHeight;
920 break;
921 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700922 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
923 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
924 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800925 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700926 naturalDeviceWidth = mViewport.deviceHeight;
927 naturalDeviceHeight = mViewport.deviceWidth;
928 break;
929 case DISPLAY_ORIENTATION_0:
930 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
932 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
933 naturalPhysicalLeft = mViewport.physicalLeft;
934 naturalPhysicalTop = mViewport.physicalTop;
935 naturalDeviceWidth = mViewport.deviceWidth;
936 naturalDeviceHeight = mViewport.deviceHeight;
937 break;
938 }
939
940 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
941 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
942 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
943 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
944 }
945
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000946 mPhysicalFrameInDisplay = Rect{naturalPhysicalLeft, naturalPhysicalTop,
947 naturalPhysicalLeft + naturalPhysicalWidth,
948 naturalPhysicalTop + naturalPhysicalHeight};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700949
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000950 const auto oldDisplayBounds = mDisplayBounds;
951 mDisplayBounds = ui::Size{naturalDeviceWidth, naturalDeviceHeight};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700952
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000953 // InputReader works in the un-rotated display coordinate space, so we don't need to do
954 // anything if the device is already orientation-aware. If the device is not
955 // orientation-aware, then we need to apply the inverse rotation of the display so that
956 // when the display rotation is applied later as a part of the per-window transform, we
957 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700958 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000959 ? DISPLAY_ORIENTATION_0
960 : getInverseRotation(mViewport.orientation);
961 // For orientation-aware devices that work in the un-rotated coordinate space, the
962 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000963 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000964 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700965
966 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700967 mInputDeviceOrientation =
968 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700969 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000970 mDisplayBounds = rawSize;
971 mPhysicalFrameInDisplay = Rect{mDisplayBounds};
Prabir Pradhan1728b212021-10-19 16:00:03 -0700972 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700973 }
974 }
975
976 // If moving between pointer modes, need to reset some state.
977 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
978 if (deviceModeChanged) {
979 mOrientedRanges.clear();
980 }
981
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800982 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
983 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100984 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800985 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000986 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
987 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800988 if (mPointerController == nullptr) {
989 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000991 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800992 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
993 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994 } else {
lilinnandef700b2022-06-17 19:32:01 +0800995 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
996 !mConfig.showTouches) {
997 mPointerController->clearSpots();
998 }
Michael Wright17db18e2020-06-26 20:51:44 +0100999 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001000 }
1001
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001002 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001003 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001005 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001006 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001007
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008 configureVirtualKeys();
1009
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001010 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011
1012 // Location
1013 updateAffineTransformation();
1014
Michael Wright227c5542020-07-02 18:30:52 +01001015 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001016 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001017 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1018 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001019
1020 // Scale movements such that one whole swipe of the touch pad covers a
1021 // given area relative to the diagonal size of the display when no acceleration
1022 // is applied.
1023 // Assume that the touch pad has a square aspect ratio such that movements in
1024 // X and Y of the same number of raw units cover the same physical distance.
1025 mPointerXMovementScale =
1026 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1027 mPointerYMovementScale = mPointerXMovementScale;
1028
1029 // Scale zooms to cover a smaller range of the display than movements do.
1030 // This value determines the area around the pointer that is affected by freeform
1031 // pointer gestures.
1032 mPointerXZoomScale =
1033 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1034 mPointerYZoomScale = mPointerXZoomScale;
1035
HQ Liue6983c72022-04-19 22:14:56 +00001036 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1037 // axis is non positive value.
1038 const float minFreeformGestureWidth =
1039 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1040
1041 mPointerGestureMaxSwipeWidth =
1042 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1043 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001044 }
1045
1046 // Inform the dispatcher about the changes.
1047 *outResetNeeded = true;
1048 bumpGeneration();
1049 }
1050}
1051
Prabir Pradhan1728b212021-10-19 16:00:03 -07001052void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001054 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
1055 dump += StringPrintf(INDENT3 "PhysicalFrame: %s\n", toString(mPhysicalFrameInDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001056 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057}
1058
1059void TouchInputMapper::configureVirtualKeys() {
1060 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001061 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062
1063 mVirtualKeys.clear();
1064
1065 if (virtualKeyDefinitions.size() == 0) {
1066 return;
1067 }
1068
1069 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1070 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1071 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1072 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1073
1074 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1075 VirtualKey virtualKey;
1076
1077 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1078 int32_t keyCode;
1079 int32_t dummyKeyMetaState;
1080 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001081 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1082 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001083 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1084 continue; // drop the key
1085 }
1086
1087 virtualKey.keyCode = keyCode;
1088 virtualKey.flags = flags;
1089
1090 // convert the key definition's display coordinates into touch coordinates for a hit box
1091 int32_t halfWidth = virtualKeyDefinition.width / 2;
1092 int32_t halfHeight = virtualKeyDefinition.height / 2;
1093
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001094 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1095 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001096 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001097 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1098 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001099 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001100 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1101 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001102 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001103 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1104 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105 touchScreenTop;
1106 mVirtualKeys.push_back(virtualKey);
1107 }
1108}
1109
1110void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1111 if (!mVirtualKeys.empty()) {
1112 dump += INDENT3 "Virtual Keys:\n";
1113
1114 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1115 const VirtualKey& virtualKey = mVirtualKeys[i];
1116 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1117 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1118 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1119 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1120 }
1121 }
1122}
1123
1124void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001125 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 Calibration& out = mCalibration;
1127
1128 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001129 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001130 std::string sizeCalibrationString;
1131 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001133 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001134 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001135 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001137 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001139 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001140 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001141 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001143 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 }
1145 }
1146
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001147 float sizeScale;
1148
1149 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1150 out.sizeScale = sizeScale;
1151 }
1152 float sizeBias;
1153 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1154 out.sizeBias = sizeBias;
1155 }
1156 bool sizeIsSummed;
1157 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1158 out.sizeIsSummed = sizeIsSummed;
1159 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160
1161 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001163 std::string pressureCalibrationString;
1164 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 } else if (pressureCalibrationString != "default") {
1172 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001173 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 }
1175 }
1176
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001177 float pressureScale;
1178 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1179 out.pressureScale = pressureScale;
1180 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181
1182 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001184 std::string orientationCalibrationString;
1185 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 } else if (orientationCalibrationString != "default") {
1193 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001194 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 }
1196 }
1197
1198 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001200 std::string distanceCalibrationString;
1201 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001203 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001206 } else if (distanceCalibrationString != "default") {
1207 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001208 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 }
1210 }
1211
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001212 float distanceScale;
1213 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1214 out.distanceScale = distanceScale;
1215 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001218 std::string coverageCalibrationString;
1219 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001223 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 } else if (coverageCalibrationString != "default") {
1225 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001226 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 }
1228 }
1229}
1230
1231void TouchInputMapper::resolveCalibration() {
1232 // Size
1233 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001234 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1235 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 }
1237 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001238 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 }
1240
1241 // Pressure
1242 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001243 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1244 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 }
1246 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001247 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249
1250 // Orientation
1251 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001252 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1253 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 }
1255 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001256 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258
1259 // Distance
1260 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001261 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1262 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 }
1264 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001265 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267
1268 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001269 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1270 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272}
1273
1274void TouchInputMapper::dumpCalibration(std::string& dump) {
1275 dump += INDENT3 "Calibration:\n";
1276
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001277 dump += INDENT4 "touch.size.calibration: ";
1278 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001280 if (mCalibration.sizeScale) {
1281 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 }
1283
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001284 if (mCalibration.sizeBias) {
1285 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286 }
1287
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001288 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001290 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 }
1292
1293 // Pressure
1294 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001295 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 dump += INDENT4 "touch.pressure.calibration: none\n";
1297 break;
Michael Wright227c5542020-07-02 18:30:52 +01001298 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 dump += INDENT4 "touch.pressure.calibration: physical\n";
1300 break;
Michael Wright227c5542020-07-02 18:30:52 +01001301 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001302 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1303 break;
1304 default:
1305 ALOG_ASSERT(false);
1306 }
1307
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001308 if (mCalibration.pressureScale) {
1309 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 }
1311
1312 // Orientation
1313 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001314 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.orientation.calibration: none\n";
1316 break;
Michael Wright227c5542020-07-02 18:30:52 +01001317 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1319 break;
Michael Wright227c5542020-07-02 18:30:52 +01001320 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001321 dump += INDENT4 "touch.orientation.calibration: vector\n";
1322 break;
1323 default:
1324 ALOG_ASSERT(false);
1325 }
1326
1327 // Distance
1328 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.distance.calibration: none\n";
1331 break;
Michael Wright227c5542020-07-02 18:30:52 +01001332 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333 dump += INDENT4 "touch.distance.calibration: scaled\n";
1334 break;
1335 default:
1336 ALOG_ASSERT(false);
1337 }
1338
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001339 if (mCalibration.distanceScale) {
1340 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 }
1342
1343 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001344 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001345 dump += INDENT4 "touch.coverage.calibration: none\n";
1346 break;
Michael Wright227c5542020-07-02 18:30:52 +01001347 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001348 dump += INDENT4 "touch.coverage.calibration: box\n";
1349 break;
1350 default:
1351 ALOG_ASSERT(false);
1352 }
1353}
1354
1355void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1356 dump += INDENT3 "Affine Transformation:\n";
1357
1358 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1359 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1360 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1361 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1362 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1363 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1364}
1365
1366void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001367 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001368 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001369}
1370
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001371std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001372 std::list<NotifyArgs> out = cancelTouch(when, when);
1373 updateTouchSpots();
1374
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001375 mCursorButtonAccumulator.reset(getDeviceContext());
1376 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001377 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378
1379 mPointerVelocityControl.reset();
1380 mWheelXVelocityControl.reset();
1381 mWheelYVelocityControl.reset();
1382
1383 mRawStatesPending.clear();
1384 mCurrentRawState.clear();
1385 mCurrentCookedState.clear();
1386 mLastRawState.clear();
1387 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001388 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001389 mSentHoverEnter = false;
1390 mHavePointerIds = false;
1391 mCurrentMotionAborted = false;
1392 mDownTime = 0;
1393
1394 mCurrentVirtualKey.down = false;
1395
1396 mPointerGesture.reset();
1397 mPointerSimple.reset();
1398 resetExternalStylus();
1399
1400 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001401 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001402 mPointerController->clearSpots();
1403 }
1404
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001405 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001406}
1407
1408void TouchInputMapper::resetExternalStylus() {
1409 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001410 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411 mExternalStylusFusionTimeout = LLONG_MAX;
1412 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001413 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001414}
1415
1416void TouchInputMapper::clearStylusDataPendingFlags() {
1417 mExternalStylusDataPending = false;
1418 mExternalStylusFusionTimeout = LLONG_MAX;
1419}
1420
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001421std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422 mCursorButtonAccumulator.process(rawEvent);
1423 mCursorScrollAccumulator.process(rawEvent);
1424 mTouchButtonAccumulator.process(rawEvent);
1425
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001426 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001428 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001429 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001430 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431}
1432
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001433std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1434 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001435 if (mDeviceMode == DeviceMode::DISABLED) {
1436 // Only save the last pending state when the device is disabled.
1437 mRawStatesPending.clear();
1438 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439 // Push a new state.
1440 mRawStatesPending.emplace_back();
1441
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001442 RawState& next = mRawStatesPending.back();
1443 next.clear();
1444 next.when = when;
1445 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446
1447 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001448 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001449 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1450
1451 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001452 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1453 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001454 mCursorScrollAccumulator.finishSync();
1455
1456 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001457 syncTouch(when, &next);
1458
1459 // The last RawState is the actually second to last, since we just added a new state
1460 const RawState& last =
1461 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001462
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001463 std::tie(next.when, next.readTime) =
1464 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1465 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001466
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001467 // Assign pointer ids.
1468 if (!mHavePointerIds) {
1469 assignPointerIds(last, next);
1470 }
1471
Harry Cutts45483602022-08-24 14:36:48 +00001472 ALOGD_IF(DEBUG_RAW_EVENTS,
1473 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1474 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1475 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1476 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1477 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1478 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479
Arthur Hung9ad18942021-06-19 02:04:46 +00001480 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1481 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1482 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1483 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1484 next.rawPointerData.hoveringIdBits.value);
1485 }
1486
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001487 out += processRawTouches(false /*timeout*/);
1488 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001489}
1490
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001491std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1492 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001493 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001494 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001495 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496 }
1497
1498 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1499 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1500 // touching the current state will only observe the events that have been dispatched to the
1501 // rest of the pipeline.
1502 const size_t N = mRawStatesPending.size();
1503 size_t count;
1504 for (count = 0; count < N; count++) {
1505 const RawState& next = mRawStatesPending[count];
1506
1507 // A failure to assign the stylus id means that we're waiting on stylus data
1508 // and so should defer the rest of the pipeline.
1509 if (assignExternalStylusId(next, timeout)) {
1510 break;
1511 }
1512
1513 // All ready to go.
1514 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001515 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001516 if (mCurrentRawState.when < mLastRawState.when) {
1517 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001518 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001519 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001520 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521 }
1522 if (count != 0) {
1523 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1524 }
1525
1526 if (mExternalStylusDataPending) {
1527 if (timeout) {
1528 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1529 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001530 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001531 ALOGD_IF(DEBUG_STYLUS_FUSION,
1532 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001533 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001534 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001535 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1536 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1537 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1538 }
1539 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001540 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001541}
1542
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001543std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1544 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001545 // Always start with a clean state.
1546 mCurrentCookedState.clear();
1547
1548 // Apply stylus buttons to current raw state.
1549 applyExternalStylusButtonState(when);
1550
1551 // Handle policy on initial down or hover events.
1552 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1553 mCurrentRawState.rawPointerData.pointerCount != 0;
1554
1555 uint32_t policyFlags = 0;
1556 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1557 if (initialDown || buttonsPressed) {
1558 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001559 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001560 getContext()->fadePointer();
1561 }
1562
1563 if (mParameters.wake) {
1564 policyFlags |= POLICY_FLAG_WAKE;
1565 }
1566 }
1567
1568 // Consume raw off-screen touches before cooking pointer data.
1569 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001570 bool consumed;
1571 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1572 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001573 mCurrentRawState.rawPointerData.clear();
1574 }
1575
1576 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1577 // with cooked pointer data that has the same ids and indices as the raw data.
1578 // The following code can use either the raw or cooked data, as needed.
1579 cookPointerData();
1580
1581 // Apply stylus pressure to current cooked state.
1582 applyExternalStylusTouchState(when);
1583
1584 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001585 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1586 mSource, mViewport.displayId, policyFlags,
1587 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001588
1589 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001590 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1592 uint32_t id = idBits.clearFirstMarkedBit();
1593 const RawPointerData::Pointer& pointer =
1594 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001595 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596 mCurrentCookedState.stylusIdBits.markBit(id);
1597 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1598 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1599 mCurrentCookedState.fingerIdBits.markBit(id);
1600 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1601 mCurrentCookedState.mouseIdBits.markBit(id);
1602 }
1603 }
1604 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1605 uint32_t id = idBits.clearFirstMarkedBit();
1606 const RawPointerData::Pointer& pointer =
1607 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001608 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001609 mCurrentCookedState.stylusIdBits.markBit(id);
1610 }
1611 }
1612
1613 // Stylus takes precedence over all tools, then mouse, then finger.
1614 PointerUsage pointerUsage = mPointerUsage;
1615 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1616 mCurrentCookedState.mouseIdBits.clear();
1617 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001618 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001619 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1620 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001621 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001622 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1623 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001624 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625 }
1626
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001627 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001630 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001631 out += dispatchButtonRelease(when, readTime, policyFlags);
1632 out += dispatchHoverExit(when, readTime, policyFlags);
1633 out += dispatchTouches(when, readTime, policyFlags);
1634 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1635 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636 }
1637
1638 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1639 mCurrentMotionAborted = false;
1640 }
1641 }
1642
1643 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001644 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1645 mSource, mViewport.displayId, policyFlags,
1646 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647
1648 // Clear some transient state.
1649 mCurrentRawState.rawVScroll = 0;
1650 mCurrentRawState.rawHScroll = 0;
1651
1652 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001653 mLastRawState = mCurrentRawState;
1654 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001655 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001656}
1657
Garfield Tanc734e4f2021-01-15 20:01:39 -08001658void TouchInputMapper::updateTouchSpots() {
1659 if (!mConfig.showTouches || mPointerController == nullptr) {
1660 return;
1661 }
1662
1663 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1664 // clear touch spots.
1665 if (mDeviceMode != DeviceMode::DIRECT &&
1666 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1667 return;
1668 }
1669
1670 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1671 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1672
1673 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001674 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1675 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001676 mCurrentCookedState.cookedPointerData.touchingIdBits,
1677 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001678}
1679
1680bool TouchInputMapper::isTouchScreen() {
1681 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1682 mParameters.hasAssociatedDisplay;
1683}
1684
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001685void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001686 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1687 // If any of the external buttons are already pressed by the touch device, ignore them.
1688 const int32_t pressedButtons = ~mCurrentRawState.buttonState & mExternalStylusState.buttons;
1689 const int32_t releasedButtons =
1690 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1691
1692 mCurrentRawState.buttonState |= pressedButtons;
1693 mCurrentRawState.buttonState &= ~releasedButtons;
1694
1695 mExternalStylusButtonsApplied |= pressedButtons;
1696 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001697 }
1698}
1699
1700void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1701 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1702 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001703 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1704 return;
1705 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001706
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001707 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1708 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1709 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1710 : 0.f;
1711 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1712 pressure = *mExternalStylusState.pressure;
1713 }
1714 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1715 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001716
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001717 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001718 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001719 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001720 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001721 }
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
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001729 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001730 if (mFusedStylusPointerId &&
1731 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001732 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001733 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001734 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001735 }
1736
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001737 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1738 state.rawPointerData.pointerCount != 0;
1739 if (!initialDown) {
1740 return false;
1741 }
1742
1743 if (!mExternalStylusState.pressure) {
1744 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1745 return false;
1746 }
1747
1748 if (*mExternalStylusState.pressure != 0.0f) {
1749 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1750 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1751 return false;
1752 }
1753
1754 if (timeout) {
1755 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1756 mFusedStylusPointerId.reset();
1757 mExternalStylusFusionTimeout = LLONG_MAX;
1758 return false;
1759 }
1760
1761 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1762 // being processed until we either get pressure data or timeout.
1763 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1764 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1765 }
1766 ALOGD_IF(DEBUG_STYLUS_FUSION,
1767 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1768 mExternalStylusFusionTimeout);
1769 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1770 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001771}
1772
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001773std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1774 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001775 if (mDeviceMode == DeviceMode::POINTER) {
1776 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001777 // Since this is a synthetic event, we can consider its latency to be zero
1778 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001779 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780 }
Michael Wright227c5542020-07-02 18:30:52 +01001781 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001782 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001783 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001784 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1785 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1786 }
1787 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001788 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001789}
1790
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001791std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1792 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001793 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001794 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001795 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001796 // The following three cases are handled here:
1797 // - We're in the middle of a fused stream of data;
1798 // - We're waiting on external stylus data before dispatching the initial down; or
1799 // - Only the button state, which is not reported through a specific pointer, has changed.
1800 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001801 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001802 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001803 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001804 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001805}
1806
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001807std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1808 uint32_t policyFlags, bool& outConsumed) {
1809 outConsumed = false;
1810 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001811 // Check for release of a virtual key.
1812 if (mCurrentVirtualKey.down) {
1813 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1814 // Pointer went up while virtual key was down.
1815 mCurrentVirtualKey.down = false;
1816 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001817 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1818 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1819 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001820 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1821 AKEY_EVENT_FLAG_FROM_SYSTEM |
1822 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001823 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001824 outConsumed = true;
1825 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001826 }
1827
1828 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1829 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1830 const RawPointerData::Pointer& pointer =
1831 mCurrentRawState.rawPointerData.pointerForId(id);
1832 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1833 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1834 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001835 outConsumed = true;
1836 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001837 }
1838 }
1839
1840 // Pointer left virtual key area or another pointer also went down.
1841 // Send key cancellation but do not consume the touch yet.
1842 // This is useful when the user swipes through from the virtual key area
1843 // into the main display surface.
1844 mCurrentVirtualKey.down = false;
1845 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001846 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1847 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001848 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1849 AKEY_EVENT_FLAG_FROM_SYSTEM |
1850 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1851 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001852 }
1853 }
1854
1855 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1856 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1857 // Pointer just went down. Check for virtual key press or off-screen touches.
1858 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1859 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001860 // Skip checking whether the pointer is inside the physical frame if the device is in
1861 // unscaled mode.
1862 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1863 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001864 // If exactly one pointer went down, check for virtual key hit.
1865 // Otherwise we will drop the entire stroke.
1866 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1867 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1868 if (virtualKey) {
1869 mCurrentVirtualKey.down = true;
1870 mCurrentVirtualKey.downTime = when;
1871 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1872 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1873 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001874 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1875 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001876
1877 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001878 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1879 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1880 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001881 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1882 AKEY_EVENT_ACTION_DOWN,
1883 AKEY_EVENT_FLAG_FROM_SYSTEM |
1884 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001885 }
1886 }
1887 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001888 outConsumed = true;
1889 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001890 }
1891 }
1892
1893 // Disable all virtual key touches that happen within a short time interval of the
1894 // most recent touch within the screen area. The idea is to filter out stray
1895 // virtual key presses when interacting with the touch screen.
1896 //
1897 // Problems we're trying to solve:
1898 //
1899 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1900 // virtual key area that is implemented by a separate touch panel and accidentally
1901 // triggers a virtual key.
1902 //
1903 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1904 // area and accidentally triggers a virtual key. This often happens when virtual keys
1905 // are layed out below the screen near to where the on screen keyboard's space bar
1906 // is displayed.
1907 if (mConfig.virtualKeyQuietTime > 0 &&
1908 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001909 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001910 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001911 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001912}
1913
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001914NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1915 uint32_t policyFlags, int32_t keyEventAction,
1916 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001917 int32_t keyCode = mCurrentVirtualKey.keyCode;
1918 int32_t scanCode = mCurrentVirtualKey.scanCode;
1919 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001920 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921 policyFlags |= POLICY_FLAG_VIRTUAL;
1922
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001923 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1924 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1925 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926}
1927
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001928std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1929 uint32_t policyFlags) {
1930 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001931 if (mCurrentMotionAborted) {
1932 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001933 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001934 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001935 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1936 if (!currentIdBits.isEmpty()) {
1937 int32_t metaState = getContext()->getGlobalMetaState();
1938 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001939 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001940 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1941 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001942 mCurrentCookedState.cookedPointerData.pointerProperties,
1943 mCurrentCookedState.cookedPointerData.pointerCoords,
1944 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1945 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1946 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001947 mCurrentMotionAborted = true;
1948 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001949 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001950}
1951
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001952// Updates pointer coords and properties for pointers with specified ids that have moved.
1953// Returns true if any of them changed.
1954static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1955 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1956 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1957 BitSet32 idBits) {
1958 bool changed = false;
1959 while (!idBits.isEmpty()) {
1960 uint32_t id = idBits.clearFirstMarkedBit();
1961 uint32_t inIndex = inIdToIndex[id];
1962 uint32_t outIndex = outIdToIndex[id];
1963
1964 const PointerProperties& curInProperties = inProperties[inIndex];
1965 const PointerCoords& curInCoords = inCoords[inIndex];
1966 PointerProperties& curOutProperties = outProperties[outIndex];
1967 PointerCoords& curOutCoords = outCoords[outIndex];
1968
1969 if (curInProperties != curOutProperties) {
1970 curOutProperties.copyFrom(curInProperties);
1971 changed = true;
1972 }
1973
1974 if (curInCoords != curOutCoords) {
1975 curOutCoords.copyFrom(curInCoords);
1976 changed = true;
1977 }
1978 }
1979 return changed;
1980}
1981
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001982std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1983 uint32_t policyFlags) {
1984 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001985 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1986 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1987 int32_t metaState = getContext()->getGlobalMetaState();
1988 int32_t buttonState = mCurrentCookedState.buttonState;
1989
1990 if (currentIdBits == lastIdBits) {
1991 if (!currentIdBits.isEmpty()) {
1992 // No pointer id changes so this is a move event.
1993 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001994 out.push_back(
1995 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1996 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1997 mCurrentCookedState.cookedPointerData.pointerProperties,
1998 mCurrentCookedState.cookedPointerData.pointerCoords,
1999 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2000 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2001 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002002 }
2003 } else {
2004 // There may be pointers going up and pointers going down and pointers moving
2005 // all at the same time.
2006 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2007 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2008 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2009 BitSet32 dispatchedIdBits(lastIdBits.value);
2010
2011 // Update last coordinates of pointers that have moved so that we observe the new
2012 // pointer positions at the same time as other pointers that have just gone up.
2013 bool moveNeeded =
2014 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2015 mCurrentCookedState.cookedPointerData.pointerCoords,
2016 mCurrentCookedState.cookedPointerData.idToIndex,
2017 mLastCookedState.cookedPointerData.pointerProperties,
2018 mLastCookedState.cookedPointerData.pointerCoords,
2019 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2020 if (buttonState != mLastCookedState.buttonState) {
2021 moveNeeded = true;
2022 }
2023
2024 // Dispatch pointer up events.
2025 while (!upIdBits.isEmpty()) {
2026 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002027 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002028 if (isCanceled) {
2029 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2030 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002031 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2032 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2033 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2034 buttonState, 0,
2035 mLastCookedState.cookedPointerData.pointerProperties,
2036 mLastCookedState.cookedPointerData.pointerCoords,
2037 mLastCookedState.cookedPointerData.idToIndex,
2038 dispatchedIdBits, upId, mOrientedXPrecision,
2039 mOrientedYPrecision, mDownTime,
2040 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002041 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002042 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002043 }
2044
2045 // Dispatch move events if any of the remaining pointers moved from their old locations.
2046 // Although applications receive new locations as part of individual pointer up
2047 // events, they do not generally handle them except when presented in a move event.
2048 if (moveNeeded && !moveIdBits.isEmpty()) {
2049 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002050 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2051 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2052 mCurrentCookedState.cookedPointerData.pointerProperties,
2053 mCurrentCookedState.cookedPointerData.pointerCoords,
2054 mCurrentCookedState.cookedPointerData.idToIndex,
2055 dispatchedIdBits, -1, mOrientedXPrecision,
2056 mOrientedYPrecision, mDownTime,
2057 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002058 }
2059
2060 // Dispatch pointer down events using the new pointer locations.
2061 while (!downIdBits.isEmpty()) {
2062 uint32_t downId = downIdBits.clearFirstMarkedBit();
2063 dispatchedIdBits.markBit(downId);
2064
2065 if (dispatchedIdBits.count() == 1) {
2066 // First pointer is going down. Set down time.
2067 mDownTime = when;
2068 }
2069
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002070 out.push_back(
2071 dispatchMotion(when, readTime, policyFlags, mSource,
2072 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2073 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2074 mCurrentCookedState.cookedPointerData.pointerCoords,
2075 mCurrentCookedState.cookedPointerData.idToIndex,
2076 dispatchedIdBits, downId, mOrientedXPrecision,
2077 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002078 }
2079 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002080 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002081}
2082
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002083std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2084 uint32_t policyFlags) {
2085 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002086 if (mSentHoverEnter &&
2087 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2088 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2089 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002090 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2091 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2092 mLastCookedState.buttonState, 0,
2093 mLastCookedState.cookedPointerData.pointerProperties,
2094 mLastCookedState.cookedPointerData.pointerCoords,
2095 mLastCookedState.cookedPointerData.idToIndex,
2096 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2097 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2098 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002099 mSentHoverEnter = false;
2100 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002101 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002102}
2103
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002104std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2105 uint32_t policyFlags) {
2106 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002107 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2108 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2109 int32_t metaState = getContext()->getGlobalMetaState();
2110 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002111 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2112 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2113 mCurrentRawState.buttonState, 0,
2114 mCurrentCookedState.cookedPointerData.pointerProperties,
2115 mCurrentCookedState.cookedPointerData.pointerCoords,
2116 mCurrentCookedState.cookedPointerData.idToIndex,
2117 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2118 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2119 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002120 mSentHoverEnter = true;
2121 }
2122
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002123 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2124 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2125 mCurrentRawState.buttonState, 0,
2126 mCurrentCookedState.cookedPointerData.pointerProperties,
2127 mCurrentCookedState.cookedPointerData.pointerCoords,
2128 mCurrentCookedState.cookedPointerData.idToIndex,
2129 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2130 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2131 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002132 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002133 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002134}
2135
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002136std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2137 uint32_t policyFlags) {
2138 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002139 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2140 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2141 const int32_t metaState = getContext()->getGlobalMetaState();
2142 int32_t buttonState = mLastCookedState.buttonState;
2143 while (!releasedButtons.isEmpty()) {
2144 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2145 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002146 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2147 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2148 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002149 mLastCookedState.cookedPointerData.pointerProperties,
2150 mLastCookedState.cookedPointerData.pointerCoords,
2151 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002152 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2153 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002155 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002156}
2157
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002158std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2159 uint32_t policyFlags) {
2160 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002161 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2162 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2163 const int32_t metaState = getContext()->getGlobalMetaState();
2164 int32_t buttonState = mLastCookedState.buttonState;
2165 while (!pressedButtons.isEmpty()) {
2166 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2167 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002168 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2169 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2170 buttonState, 0,
2171 mCurrentCookedState.cookedPointerData.pointerProperties,
2172 mCurrentCookedState.cookedPointerData.pointerCoords,
2173 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2174 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2175 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002176 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002177 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002178}
2179
2180const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2181 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2182 return cookedPointerData.touchingIdBits;
2183 }
2184 return cookedPointerData.hoveringIdBits;
2185}
2186
2187void TouchInputMapper::cookPointerData() {
2188 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2189
2190 mCurrentCookedState.cookedPointerData.clear();
2191 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2192 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2193 mCurrentRawState.rawPointerData.hoveringIdBits;
2194 mCurrentCookedState.cookedPointerData.touchingIdBits =
2195 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002196 mCurrentCookedState.cookedPointerData.canceledIdBits =
2197 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002198
2199 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2200 mCurrentCookedState.buttonState = 0;
2201 } else {
2202 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2203 }
2204
2205 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002206 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002207 for (uint32_t i = 0; i < currentPointerCount; i++) {
2208 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2209
2210 // Size
2211 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2212 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002213 case Calibration::SizeCalibration::GEOMETRIC:
2214 case Calibration::SizeCalibration::DIAMETER:
2215 case Calibration::SizeCalibration::BOX:
2216 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002217 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2218 touchMajor = in.touchMajor;
2219 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2220 toolMajor = in.toolMajor;
2221 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2222 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2223 : in.touchMajor;
2224 } else if (mRawPointerAxes.touchMajor.valid) {
2225 toolMajor = touchMajor = in.touchMajor;
2226 toolMinor = touchMinor =
2227 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2228 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2229 : in.touchMajor;
2230 } else if (mRawPointerAxes.toolMajor.valid) {
2231 touchMajor = toolMajor = in.toolMajor;
2232 touchMinor = toolMinor =
2233 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2234 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2235 : in.toolMajor;
2236 } else {
2237 ALOG_ASSERT(false,
2238 "No touch or tool axes. "
2239 "Size calibration should have been resolved to NONE.");
2240 touchMajor = 0;
2241 touchMinor = 0;
2242 toolMajor = 0;
2243 toolMinor = 0;
2244 size = 0;
2245 }
2246
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002247 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002248 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2249 if (touchingCount > 1) {
2250 touchMajor /= touchingCount;
2251 touchMinor /= touchingCount;
2252 toolMajor /= touchingCount;
2253 toolMinor /= touchingCount;
2254 size /= touchingCount;
2255 }
2256 }
2257
Michael Wright227c5542020-07-02 18:30:52 +01002258 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002259 touchMajor *= mGeometricScale;
2260 touchMinor *= mGeometricScale;
2261 toolMajor *= mGeometricScale;
2262 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002263 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002264 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2265 touchMinor = touchMajor;
2266 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2267 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002268 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002269 touchMinor = touchMajor;
2270 toolMinor = toolMajor;
2271 }
2272
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002273 mCalibration.applySizeScaleAndBias(touchMajor);
2274 mCalibration.applySizeScaleAndBias(touchMinor);
2275 mCalibration.applySizeScaleAndBias(toolMajor);
2276 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002277 size *= mSizeScale;
2278 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002279 case Calibration::SizeCalibration::DEFAULT:
2280 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2281 break;
2282 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002283 touchMajor = 0;
2284 touchMinor = 0;
2285 toolMajor = 0;
2286 toolMinor = 0;
2287 size = 0;
2288 break;
2289 }
2290
2291 // Pressure
2292 float pressure;
2293 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002294 case Calibration::PressureCalibration::PHYSICAL:
2295 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 pressure = in.pressure * mPressureScale;
2297 break;
2298 default:
2299 pressure = in.isHovering ? 0 : 1;
2300 break;
2301 }
2302
2303 // Tilt and Orientation
2304 float tilt;
2305 float orientation;
2306 if (mHaveTilt) {
2307 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2308 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2309 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2310 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2311 } else {
2312 tilt = 0;
2313
2314 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002315 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002316 orientation = in.orientation * mOrientationScale;
2317 break;
Michael Wright227c5542020-07-02 18:30:52 +01002318 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002319 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2320 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2321 if (c1 != 0 || c2 != 0) {
2322 orientation = atan2f(c1, c2) * 0.5f;
2323 float confidence = hypotf(c1, c2);
2324 float scale = 1.0f + confidence / 16.0f;
2325 touchMajor *= scale;
2326 touchMinor /= scale;
2327 toolMajor *= scale;
2328 toolMinor /= scale;
2329 } else {
2330 orientation = 0;
2331 }
2332 break;
2333 }
2334 default:
2335 orientation = 0;
2336 }
2337 }
2338
2339 // Distance
2340 float distance;
2341 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002342 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 distance = in.distance * mDistanceScale;
2344 break;
2345 default:
2346 distance = 0;
2347 }
2348
2349 // Coverage
2350 int32_t rawLeft, rawTop, rawRight, rawBottom;
2351 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002352 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2354 rawRight = in.toolMinor & 0x0000ffff;
2355 rawBottom = in.toolMajor & 0x0000ffff;
2356 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2357 break;
2358 default:
2359 rawLeft = rawTop = rawRight = rawBottom = 0;
2360 break;
2361 }
2362
2363 // Adjust X,Y coords for device calibration
2364 // TODO: Adjust coverage coords?
2365 float xTransformed = in.x, yTransformed = in.y;
2366 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002367 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368
Prabir Pradhan1728b212021-10-19 16:00:03 -07002369 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 float left, top, right, bottom;
2371
Prabir Pradhan1728b212021-10-19 16:00:03 -07002372 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002374 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2375 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2376 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2377 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002379 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002381 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 }
2383 break;
2384 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2386 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002387 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2388 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002390 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002392 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393 }
2394 break;
2395 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2397 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002398 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2399 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002401 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002403 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 }
2405 break;
2406 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002407 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2408 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2409 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2410 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 break;
2412 }
2413
2414 // Write output coords.
2415 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2416 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002417 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2418 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2420 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2421 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2422 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2423 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2424 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2425 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002426 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2428 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2429 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2430 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2431 } else {
2432 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2433 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2434 }
2435
Chris Ye364fdb52020-08-05 15:07:56 -07002436 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002437 uint32_t id = in.id;
2438 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2439 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2440 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2441 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2442 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2443 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2444 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2445 }
2446
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002447 // Write output properties.
2448 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002449 properties.clear();
2450 properties.id = id;
2451 properties.toolType = in.toolType;
2452
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002453 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002455 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 }
2457}
2458
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002459std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2460 uint32_t policyFlags,
2461 PointerUsage pointerUsage) {
2462 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002464 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 mPointerUsage = pointerUsage;
2466 }
2467
2468 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002469 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002470 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002471 break;
Michael Wright227c5542020-07-02 18:30:52 +01002472 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 break;
Michael Wright227c5542020-07-02 18:30:52 +01002475 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002476 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002477 break;
Michael Wright227c5542020-07-02 18:30:52 +01002478 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 break;
2480 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002481 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002482}
2483
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002484std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2485 uint32_t policyFlags) {
2486 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002487 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002488 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002489 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 break;
Michael Wright227c5542020-07-02 18:30:52 +01002491 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002492 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002493 break;
Michael Wright227c5542020-07-02 18:30:52 +01002494 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002495 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496 break;
Michael Wright227c5542020-07-02 18:30:52 +01002497 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002498 break;
2499 }
2500
Michael Wright227c5542020-07-02 18:30:52 +01002501 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002502 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503}
2504
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002505std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2506 uint32_t policyFlags,
2507 bool isTimeout) {
2508 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 // Update current gesture coordinates.
2510 bool cancelPreviousGesture, finishPreviousGesture;
2511 bool sendEvents =
2512 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2513 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002514 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002515 }
2516 if (finishPreviousGesture) {
2517 cancelPreviousGesture = false;
2518 }
2519
2520 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002521 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002522 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002523 if (finishPreviousGesture || cancelPreviousGesture) {
2524 mPointerController->clearSpots();
2525 }
2526
Michael Wright227c5542020-07-02 18:30:52 +01002527 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002528 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2529 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002530 mPointerGesture.currentGestureIdBits,
2531 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002532 }
2533 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002534 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535 }
2536
2537 // Show or hide the pointer if needed.
2538 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002539 case PointerGesture::Mode::NEUTRAL:
2540 case PointerGesture::Mode::QUIET:
2541 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2542 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002543 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002544 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002545 }
2546 break;
Michael Wright227c5542020-07-02 18:30:52 +01002547 case PointerGesture::Mode::TAP:
2548 case PointerGesture::Mode::TAP_DRAG:
2549 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2550 case PointerGesture::Mode::HOVER:
2551 case PointerGesture::Mode::PRESS:
2552 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 // Unfade the pointer when the current gesture manipulates the
2554 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002555 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002556 break;
Michael Wright227c5542020-07-02 18:30:52 +01002557 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002558 // Fade the pointer when the current gesture manipulates a different
2559 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002560 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002561 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002562 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002563 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002564 }
2565 break;
2566 }
2567
2568 // Send events!
2569 int32_t metaState = getContext()->getGlobalMetaState();
2570 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002571 const MotionClassification classification =
2572 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2573 ? MotionClassification::TWO_FINGER_SWIPE
2574 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002575
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002576 uint32_t flags = 0;
2577
2578 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2579 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2580 }
2581
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002582 // Update last coordinates of pointers that have moved so that we observe the new
2583 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002584 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2585 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2586 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2587 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2588 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2589 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002590 bool moveNeeded = false;
2591 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2592 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2593 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2594 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2595 mPointerGesture.lastGestureIdBits.value);
2596 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2597 mPointerGesture.currentGestureCoords,
2598 mPointerGesture.currentGestureIdToIndex,
2599 mPointerGesture.lastGestureProperties,
2600 mPointerGesture.lastGestureCoords,
2601 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2602 if (buttonState != mLastCookedState.buttonState) {
2603 moveNeeded = true;
2604 }
2605 }
2606
2607 // Send motion events for all pointers that went up or were canceled.
2608 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2609 if (!dispatchedGestureIdBits.isEmpty()) {
2610 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002611 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002612 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002613 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002614 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2615 mPointerGesture.lastGestureProperties,
2616 mPointerGesture.lastGestureCoords,
2617 mPointerGesture.lastGestureIdToIndex,
2618 dispatchedGestureIdBits, -1, 0, 0,
2619 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002620
2621 dispatchedGestureIdBits.clear();
2622 } else {
2623 BitSet32 upGestureIdBits;
2624 if (finishPreviousGesture) {
2625 upGestureIdBits = dispatchedGestureIdBits;
2626 } else {
2627 upGestureIdBits.value =
2628 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2629 }
2630 while (!upGestureIdBits.isEmpty()) {
2631 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2632
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002633 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2634 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2635 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2636 mPointerGesture.lastGestureProperties,
2637 mPointerGesture.lastGestureCoords,
2638 mPointerGesture.lastGestureIdToIndex,
2639 dispatchedGestureIdBits, id, 0, 0,
2640 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002641
2642 dispatchedGestureIdBits.clearBit(id);
2643 }
2644 }
2645 }
2646
2647 // Send motion events for all pointers that moved.
2648 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002649 out.push_back(
2650 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2651 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2652 mPointerGesture.currentGestureProperties,
2653 mPointerGesture.currentGestureCoords,
2654 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2655 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002656 }
2657
2658 // Send motion events for all pointers that went down.
2659 if (down) {
2660 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2661 ~dispatchedGestureIdBits.value);
2662 while (!downGestureIdBits.isEmpty()) {
2663 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2664 dispatchedGestureIdBits.markBit(id);
2665
2666 if (dispatchedGestureIdBits.count() == 1) {
2667 mPointerGesture.downTime = when;
2668 }
2669
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002670 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2671 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2672 buttonState, 0, mPointerGesture.currentGestureProperties,
2673 mPointerGesture.currentGestureCoords,
2674 mPointerGesture.currentGestureIdToIndex,
2675 dispatchedGestureIdBits, id, 0, 0,
2676 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002677 }
2678 }
2679
2680 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002681 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002682 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2683 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2684 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2685 mPointerGesture.currentGestureProperties,
2686 mPointerGesture.currentGestureCoords,
2687 mPointerGesture.currentGestureIdToIndex,
2688 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2689 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002690 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2691 // Synthesize a hover move event after all pointers go up to indicate that
2692 // the pointer is hovering again even if the user is not currently touching
2693 // the touch pad. This ensures that a view will receive a fresh hover enter
2694 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002695 float x, y;
2696 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002697
2698 PointerProperties pointerProperties;
2699 pointerProperties.clear();
2700 pointerProperties.id = 0;
2701 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2702
2703 PointerCoords pointerCoords;
2704 pointerCoords.clear();
2705 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2706 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2707
2708 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002709 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2710 mSource, displayId, policyFlags,
2711 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2712 buttonState, MotionClassification::NONE,
2713 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2714 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2715 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002716 }
2717
2718 // Update state.
2719 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2720 if (!down) {
2721 mPointerGesture.lastGestureIdBits.clear();
2722 } else {
2723 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2724 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2725 uint32_t id = idBits.clearFirstMarkedBit();
2726 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2727 mPointerGesture.lastGestureProperties[index].copyFrom(
2728 mPointerGesture.currentGestureProperties[index]);
2729 mPointerGesture.lastGestureCoords[index].copyFrom(
2730 mPointerGesture.currentGestureCoords[index]);
2731 mPointerGesture.lastGestureIdToIndex[id] = index;
2732 }
2733 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002734 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002735}
2736
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002737std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2738 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002739 const MotionClassification classification =
2740 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2741 ? MotionClassification::TWO_FINGER_SWIPE
2742 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002743 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002744 // Cancel previously dispatches pointers.
2745 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2746 int32_t metaState = getContext()->getGlobalMetaState();
2747 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002748 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002749 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2750 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002751 mPointerGesture.lastGestureProperties,
2752 mPointerGesture.lastGestureCoords,
2753 mPointerGesture.lastGestureIdToIndex,
2754 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2755 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002756 }
2757
2758 // Reset the current pointer gesture.
2759 mPointerGesture.reset();
2760 mPointerVelocityControl.reset();
2761
2762 // Remove any current spots.
2763 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002764 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002765 mPointerController->clearSpots();
2766 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002767 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002768}
2769
2770bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2771 bool* outFinishPreviousGesture, bool isTimeout) {
2772 *outCancelPreviousGesture = false;
2773 *outFinishPreviousGesture = false;
2774
2775 // Handle TAP timeout.
2776 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002777 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002778
Michael Wright227c5542020-07-02 18:30:52 +01002779 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002780 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2781 // The tap/drag timeout has not yet expired.
2782 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2783 mConfig.pointerGestureTapDragInterval);
2784 } else {
2785 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002786 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787 *outFinishPreviousGesture = true;
2788
2789 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002790 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002791 mPointerGesture.currentGestureIdBits.clear();
2792
2793 mPointerVelocityControl.reset();
2794 return true;
2795 }
2796 }
2797
2798 // We did not handle this timeout.
2799 return false;
2800 }
2801
2802 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2803 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2804
2805 // Update the velocity tracker.
2806 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002807 std::vector<float> positionsX;
2808 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002809 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002810 uint32_t id = idBits.clearFirstMarkedBit();
2811 const RawPointerData::Pointer& pointer =
2812 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002813 positionsX.push_back(pointer.x * mPointerXMovementScale);
2814 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815 }
2816 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002817 {{AMOTION_EVENT_AXIS_X, positionsX},
2818 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002819 }
2820
2821 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2822 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002823 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2824 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2825 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826 mPointerGesture.resetTap();
2827 }
2828
2829 // Pick a new active touch id if needed.
2830 // Choose an arbitrary pointer that just went down, if there is one.
2831 // Otherwise choose an arbitrary remaining pointer.
2832 // This guarantees we always have an active touch id when there is at least one pointer.
2833 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002834 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002835 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002836 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002837 mPointerGesture.firstTouchTime = when;
2838 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002839 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2840 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2841 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2842 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002843 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002844 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002845
2846 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002847 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002848 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002849 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2850 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2851 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002852 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002853 *outFinishPreviousGesture = true;
2854 }
2855
2856 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002857 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002858 mPointerGesture.currentGestureIdBits.clear();
2859
2860 mPointerVelocityControl.reset();
2861 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2862 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2863 // The pointer follows the active touch point.
2864 // Emit DOWN, MOVE, UP events at the pointer location.
2865 //
2866 // Only the active touch matters; other fingers are ignored. This policy helps
2867 // to handle the case where the user places a second finger on the touch pad
2868 // to apply the necessary force to depress an integrated button below the surface.
2869 // We don't want the second finger to be delivered to applications.
2870 //
2871 // For this to work well, we need to make sure to track the pointer that is really
2872 // active. If the user first puts one finger down to click then adds another
2873 // finger to drag then the active pointer should switch to the finger that is
2874 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002875 ALOGD_IF(DEBUG_GESTURES,
2876 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2877 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002879 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002880 *outFinishPreviousGesture = true;
2881 mPointerGesture.activeGestureId = 0;
2882 }
2883
2884 // Switch pointers if needed.
2885 // Find the fastest pointer and follow it.
2886 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002887 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002888 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002889 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002890 ALOGD_IF(DEBUG_GESTURES,
2891 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2892 "bestSpeed=%0.3f",
2893 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002894 }
2895 }
2896
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002897 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002898 // When using spots, the click will occur at the position of the anchor
2899 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002900 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002901 } else {
2902 mPointerVelocityControl.reset();
2903 }
2904
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002905 float x, y;
2906 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907
Michael Wright227c5542020-07-02 18:30:52 +01002908 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002909 mPointerGesture.currentGestureIdBits.clear();
2910 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2911 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2912 mPointerGesture.currentGestureProperties[0].clear();
2913 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2914 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2915 mPointerGesture.currentGestureCoords[0].clear();
2916 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2917 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2918 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2919 } else if (currentFingerCount == 0) {
2920 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002921 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 *outFinishPreviousGesture = true;
2923 }
2924
2925 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2926 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2927 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002928 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2929 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002930 lastFingerCount == 1) {
2931 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002932 float x, y;
2933 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002934 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2935 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002936 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002937
2938 mPointerGesture.tapUpTime = when;
2939 getContext()->requestTimeoutAtTime(when +
2940 mConfig.pointerGestureTapDragInterval);
2941
2942 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002943 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 mPointerGesture.currentGestureIdBits.clear();
2945 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2946 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2947 mPointerGesture.currentGestureProperties[0].clear();
2948 mPointerGesture.currentGestureProperties[0].id =
2949 mPointerGesture.activeGestureId;
2950 mPointerGesture.currentGestureProperties[0].toolType =
2951 AMOTION_EVENT_TOOL_TYPE_FINGER;
2952 mPointerGesture.currentGestureCoords[0].clear();
2953 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2954 mPointerGesture.tapX);
2955 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2956 mPointerGesture.tapY);
2957 mPointerGesture.currentGestureCoords[0]
2958 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2959
2960 tapped = true;
2961 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002962 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2963 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002964 }
2965 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002966 if (DEBUG_GESTURES) {
2967 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2968 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2969 (when - mPointerGesture.tapDownTime) * 0.000001f);
2970 } else {
2971 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2972 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974 }
2975 }
2976
2977 mPointerVelocityControl.reset();
2978
2979 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002980 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002982 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002983 mPointerGesture.currentGestureIdBits.clear();
2984 }
2985 } else if (currentFingerCount == 1) {
2986 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2987 // The pointer follows the active touch point.
2988 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2989 // When in TAP_DRAG, emit MOVE events at the pointer location.
2990 ALOG_ASSERT(activeTouchId >= 0);
2991
Michael Wright227c5542020-07-02 18:30:52 +01002992 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2993 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002994 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002995 float x, y;
2996 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2998 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002999 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003000 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003001 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3002 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 }
3004 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003005 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3006 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003007 }
Michael Wright227c5542020-07-02 18:30:52 +01003008 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3009 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003010 }
3011
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003012 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003013 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003014 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003015 } else {
3016 mPointerVelocityControl.reset();
3017 }
3018
3019 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003020 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003021 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003022 down = true;
3023 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003024 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003025 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003026 *outFinishPreviousGesture = true;
3027 }
3028 mPointerGesture.activeGestureId = 0;
3029 down = false;
3030 }
3031
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003032 float x, y;
3033 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003034
3035 mPointerGesture.currentGestureIdBits.clear();
3036 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3037 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3038 mPointerGesture.currentGestureProperties[0].clear();
3039 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3040 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3041 mPointerGesture.currentGestureCoords[0].clear();
3042 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3043 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3044 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3045 down ? 1.0f : 0.0f);
3046
3047 if (lastFingerCount == 0 && currentFingerCount != 0) {
3048 mPointerGesture.resetTap();
3049 mPointerGesture.tapDownTime = when;
3050 mPointerGesture.tapX = x;
3051 mPointerGesture.tapY = y;
3052 }
3053 } else {
3054 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003055 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003056 }
3057
3058 mPointerController->setButtonState(mCurrentRawState.buttonState);
3059
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003060 if (DEBUG_GESTURES) {
3061 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3062 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3063 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3064 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3065 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3066 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3067 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3068 uint32_t id = idBits.clearFirstMarkedBit();
3069 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3070 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3071 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3072 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3073 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3074 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3075 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3076 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3077 }
3078 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3079 uint32_t id = idBits.clearFirstMarkedBit();
3080 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3081 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3082 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3083 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3084 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3085 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3086 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3087 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3088 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003089 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003090 return true;
3091}
3092
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003093bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3094 if (mPointerGesture.activeTouchId < 0) {
3095 mPointerGesture.resetQuietTime();
3096 return false;
3097 }
3098
3099 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3100 return true;
3101 }
3102
3103 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3104 bool isQuietTime = false;
3105 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3106 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3107 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3108 currentFingerCount < 2) {
3109 // Enter quiet time when exiting swipe or freeform state.
3110 // This is to prevent accidentally entering the hover state and flinging the
3111 // pointer when finishing a swipe and there is still one pointer left onscreen.
3112 isQuietTime = true;
3113 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3114 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3115 // Enter quiet time when releasing the button and there are still two or more
3116 // fingers down. This may indicate that one finger was used to press the button
3117 // but it has not gone up yet.
3118 isQuietTime = true;
3119 }
3120 if (isQuietTime) {
3121 mPointerGesture.quietTime = when;
3122 }
3123 return isQuietTime;
3124}
3125
3126std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3127 int32_t bestId = -1;
3128 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3129 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3130 uint32_t id = idBits.clearFirstMarkedBit();
3131 std::optional<float> vx =
3132 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3133 std::optional<float> vy =
3134 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3135 if (vx && vy) {
3136 float speed = hypotf(*vx, *vy);
3137 if (speed > bestSpeed) {
3138 bestId = id;
3139 bestSpeed = speed;
3140 }
3141 }
3142 }
3143 return std::make_pair(bestId, bestSpeed);
3144}
3145
3146void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3147 bool* finishPreviousGesture) {
3148 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3149 // to move before deciding what to do.
3150 //
3151 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3152 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3153 // just a press or long-press at the pointer location.
3154 //
3155 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3156 // pointer location.
3157 //
3158 // When the two fingers move enough or when additional fingers are added, we make a decision to
3159 // transition into SWIPE or FREEFORM mode accordingly.
3160 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3161 ALOG_ASSERT(activeTouchId >= 0);
3162
3163 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3164 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3165 bool settled =
3166 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3167 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3168 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3169 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3170 *finishPreviousGesture = true;
3171 } else if (!settled && currentFingerCount > lastFingerCount) {
3172 // Additional pointers have gone down but not yet settled.
3173 // Reset the gesture.
3174 ALOGD_IF(DEBUG_GESTURES,
3175 "Gestures: Resetting gesture since additional pointers went down for "
3176 "MULTITOUCH, settle time remaining %0.3fms",
3177 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3178 when) * 0.000001f);
3179 *cancelPreviousGesture = true;
3180 } else {
3181 // Continue previous gesture.
3182 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3183 }
3184
3185 if (*finishPreviousGesture || *cancelPreviousGesture) {
3186 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3187 mPointerGesture.activeGestureId = 0;
3188 mPointerGesture.referenceIdBits.clear();
3189 mPointerVelocityControl.reset();
3190
3191 // Use the centroid and pointer location as the reference points for the gesture.
3192 ALOGD_IF(DEBUG_GESTURES,
3193 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3194 "%0.3fms",
3195 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3196 when) * 0.000001f);
3197 mCurrentRawState.rawPointerData
3198 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3199 &mPointerGesture.referenceTouchY);
3200 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3201 &mPointerGesture.referenceGestureY);
3202 }
3203
3204 // Clear the reference deltas for fingers not yet included in the reference calculation.
3205 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3206 ~mPointerGesture.referenceIdBits.value);
3207 !idBits.isEmpty();) {
3208 uint32_t id = idBits.clearFirstMarkedBit();
3209 mPointerGesture.referenceDeltas[id].dx = 0;
3210 mPointerGesture.referenceDeltas[id].dy = 0;
3211 }
3212 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3213
3214 // Add delta for all fingers and calculate a common movement delta.
3215 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3216 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3217 mCurrentCookedState.fingerIdBits.value);
3218 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3219 bool first = (idBits == commonIdBits);
3220 uint32_t id = idBits.clearFirstMarkedBit();
3221 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3222 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3223 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3224 delta.dx += cpd.x - lpd.x;
3225 delta.dy += cpd.y - lpd.y;
3226
3227 if (first) {
3228 commonDeltaRawX = delta.dx;
3229 commonDeltaRawY = delta.dy;
3230 } else {
3231 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3232 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3233 }
3234 }
3235
3236 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3237 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3238 float dist[MAX_POINTER_ID + 1];
3239 int32_t distOverThreshold = 0;
3240 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3241 uint32_t id = idBits.clearFirstMarkedBit();
3242 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3243 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3244 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3245 distOverThreshold += 1;
3246 }
3247 }
3248
3249 // Only transition when at least two pointers have moved further than
3250 // the minimum distance threshold.
3251 if (distOverThreshold >= 2) {
3252 if (currentFingerCount > 2) {
3253 // There are more than two pointers, switch to FREEFORM.
3254 ALOGD_IF(DEBUG_GESTURES,
3255 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3256 currentFingerCount);
3257 *cancelPreviousGesture = true;
3258 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3259 } else {
3260 // There are exactly two pointers.
3261 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3262 uint32_t id1 = idBits.clearFirstMarkedBit();
3263 uint32_t id2 = idBits.firstMarkedBit();
3264 const RawPointerData::Pointer& p1 =
3265 mCurrentRawState.rawPointerData.pointerForId(id1);
3266 const RawPointerData::Pointer& p2 =
3267 mCurrentRawState.rawPointerData.pointerForId(id2);
3268 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3269 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3270 // There are two pointers but they are too far apart for a SWIPE,
3271 // switch to FREEFORM.
3272 ALOGD_IF(DEBUG_GESTURES,
3273 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3274 mutualDistance, mPointerGestureMaxSwipeWidth);
3275 *cancelPreviousGesture = true;
3276 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3277 } else {
3278 // There are two pointers. Wait for both pointers to start moving
3279 // before deciding whether this is a SWIPE or FREEFORM gesture.
3280 float dist1 = dist[id1];
3281 float dist2 = dist[id2];
3282 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3283 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3284 // Calculate the dot product of the displacement vectors.
3285 // When the vectors are oriented in approximately the same direction,
3286 // the angle betweeen them is near zero and the cosine of the angle
3287 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3288 // mag(v2).
3289 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3290 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3291 float dx1 = delta1.dx * mPointerXZoomScale;
3292 float dy1 = delta1.dy * mPointerYZoomScale;
3293 float dx2 = delta2.dx * mPointerXZoomScale;
3294 float dy2 = delta2.dy * mPointerYZoomScale;
3295 float dot = dx1 * dx2 + dy1 * dy2;
3296 float cosine = dot / (dist1 * dist2); // denominator always > 0
3297 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3298 // Pointers are moving in the same direction. Switch to SWIPE.
3299 ALOGD_IF(DEBUG_GESTURES,
3300 "Gestures: PRESS transitioned to SWIPE, "
3301 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3302 "cosine %0.3f >= %0.3f",
3303 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3304 mConfig.pointerGestureMultitouchMinDistance, cosine,
3305 mConfig.pointerGestureSwipeTransitionAngleCosine);
3306 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3307 } else {
3308 // Pointers are moving in different directions. Switch to FREEFORM.
3309 ALOGD_IF(DEBUG_GESTURES,
3310 "Gestures: PRESS transitioned to FREEFORM, "
3311 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3312 "cosine %0.3f < %0.3f",
3313 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3314 mConfig.pointerGestureMultitouchMinDistance, cosine,
3315 mConfig.pointerGestureSwipeTransitionAngleCosine);
3316 *cancelPreviousGesture = true;
3317 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3318 }
3319 }
3320 }
3321 }
3322 }
3323 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3324 // Switch from SWIPE to FREEFORM if additional pointers go down.
3325 // Cancel previous gesture.
3326 if (currentFingerCount > 2) {
3327 ALOGD_IF(DEBUG_GESTURES,
3328 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3329 currentFingerCount);
3330 *cancelPreviousGesture = true;
3331 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3332 }
3333 }
3334
3335 // Move the reference points based on the overall group motion of the fingers
3336 // except in PRESS mode while waiting for a transition to occur.
3337 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3338 (commonDeltaRawX || commonDeltaRawY)) {
3339 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3340 uint32_t id = idBits.clearFirstMarkedBit();
3341 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3342 delta.dx = 0;
3343 delta.dy = 0;
3344 }
3345
3346 mPointerGesture.referenceTouchX += commonDeltaRawX;
3347 mPointerGesture.referenceTouchY += commonDeltaRawY;
3348
3349 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3350 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3351
3352 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3353 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3354
3355 mPointerGesture.referenceGestureX += commonDeltaX;
3356 mPointerGesture.referenceGestureY += commonDeltaY;
3357 }
3358
3359 // Report gestures.
3360 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3361 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3362 // PRESS or SWIPE mode.
3363 ALOGD_IF(DEBUG_GESTURES,
3364 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3365 "currentTouchPointerCount=%d",
3366 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3367 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3368
3369 mPointerGesture.currentGestureIdBits.clear();
3370 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3371 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3372 mPointerGesture.currentGestureProperties[0].clear();
3373 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3374 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3375 mPointerGesture.currentGestureCoords[0].clear();
3376 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3377 mPointerGesture.referenceGestureX);
3378 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3379 mPointerGesture.referenceGestureY);
3380 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3381 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3382 float xOffset = static_cast<float>(commonDeltaRawX) /
3383 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3384 float yOffset = static_cast<float>(commonDeltaRawY) /
3385 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3386 mPointerGesture.currentGestureCoords[0]
3387 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3388 mPointerGesture.currentGestureCoords[0]
3389 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3390 }
3391 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3392 // FREEFORM mode.
3393 ALOGD_IF(DEBUG_GESTURES,
3394 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3395 "currentTouchPointerCount=%d",
3396 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3397 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3398
3399 mPointerGesture.currentGestureIdBits.clear();
3400
3401 BitSet32 mappedTouchIdBits;
3402 BitSet32 usedGestureIdBits;
3403 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3404 // Initially, assign the active gesture id to the active touch point
3405 // if there is one. No other touch id bits are mapped yet.
3406 if (!*cancelPreviousGesture) {
3407 mappedTouchIdBits.markBit(activeTouchId);
3408 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3409 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3410 mPointerGesture.activeGestureId;
3411 } else {
3412 mPointerGesture.activeGestureId = -1;
3413 }
3414 } else {
3415 // Otherwise, assume we mapped all touches from the previous frame.
3416 // Reuse all mappings that are still applicable.
3417 mappedTouchIdBits.value =
3418 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3419 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3420
3421 // Check whether we need to choose a new active gesture id because the
3422 // current went went up.
3423 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3424 ~mCurrentCookedState.fingerIdBits.value);
3425 !upTouchIdBits.isEmpty();) {
3426 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3427 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3428 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3429 mPointerGesture.activeGestureId = -1;
3430 break;
3431 }
3432 }
3433 }
3434
3435 ALOGD_IF(DEBUG_GESTURES,
3436 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3437 "activeGestureId=%d",
3438 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3439
3440 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3441 for (uint32_t i = 0; i < currentFingerCount; i++) {
3442 uint32_t touchId = idBits.clearFirstMarkedBit();
3443 uint32_t gestureId;
3444 if (!mappedTouchIdBits.hasBit(touchId)) {
3445 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3446 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3447 ALOGD_IF(DEBUG_GESTURES,
3448 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3449 gestureId);
3450 } else {
3451 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3452 ALOGD_IF(DEBUG_GESTURES,
3453 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3454 touchId, gestureId);
3455 }
3456 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3457 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3458
3459 const RawPointerData::Pointer& pointer =
3460 mCurrentRawState.rawPointerData.pointerForId(touchId);
3461 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3462 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3463 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3464
3465 mPointerGesture.currentGestureProperties[i].clear();
3466 mPointerGesture.currentGestureProperties[i].id = gestureId;
3467 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3468 mPointerGesture.currentGestureCoords[i].clear();
3469 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3470 mPointerGesture.referenceGestureX +
3471 deltaX);
3472 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3473 mPointerGesture.referenceGestureY +
3474 deltaY);
3475 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3476 }
3477
3478 if (mPointerGesture.activeGestureId < 0) {
3479 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3480 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3481 mPointerGesture.activeGestureId);
3482 }
3483 }
3484}
3485
Harry Cutts714d1ad2022-08-24 16:36:43 +00003486void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3487 const RawPointerData::Pointer& currentPointer =
3488 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3489 const RawPointerData::Pointer& lastPointer =
3490 mLastRawState.rawPointerData.pointerForId(pointerId);
3491 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3492 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3493
3494 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3495 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3496
3497 mPointerController->move(deltaX, deltaY);
3498}
3499
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003500std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3501 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003502 mPointerSimple.currentCoords.clear();
3503 mPointerSimple.currentProperties.clear();
3504
3505 bool down, hovering;
3506 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3507 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3508 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003509 mPointerController
3510 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3511 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003512
3513 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3514 down = !hovering;
3515
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003516 float x, y;
3517 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003518 mPointerSimple.currentCoords.copyFrom(
3519 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3520 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3521 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3522 mPointerSimple.currentProperties.id = 0;
3523 mPointerSimple.currentProperties.toolType =
3524 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3525 } else {
3526 down = false;
3527 hovering = false;
3528 }
3529
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003530 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003531}
3532
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003533std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3534 uint32_t policyFlags) {
3535 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003536}
3537
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003538std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3539 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003540 mPointerSimple.currentCoords.clear();
3541 mPointerSimple.currentProperties.clear();
3542
3543 bool down, hovering;
3544 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3545 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003547 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003548 } else {
3549 mPointerVelocityControl.reset();
3550 }
3551
3552 down = isPointerDown(mCurrentRawState.buttonState);
3553 hovering = !down;
3554
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003555 float x, y;
3556 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003557 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003558 mPointerSimple.currentCoords.copyFrom(
3559 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3560 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3561 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3562 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3563 hovering ? 0.0f : 1.0f);
3564 mPointerSimple.currentProperties.id = 0;
3565 mPointerSimple.currentProperties.toolType =
3566 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3567 } else {
3568 mPointerVelocityControl.reset();
3569
3570 down = false;
3571 hovering = false;
3572 }
3573
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003574 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003575}
3576
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003577std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3578 uint32_t policyFlags) {
3579 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003580
3581 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003582
3583 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003584}
3585
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003586std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3587 uint32_t policyFlags, bool down,
3588 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003589 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3590 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003591 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003592 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593
3594 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003595 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003596 mPointerController->clearSpots();
3597 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003598 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003599 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003600 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003601 }
Garfield Tan9514d782020-11-10 16:37:23 -08003602 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003603
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003604 float xCursorPosition, yCursorPosition;
3605 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606
3607 if (mPointerSimple.down && !down) {
3608 mPointerSimple.down = false;
3609
3610 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003611 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3612 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3613 0, metaState, mLastRawState.buttonState,
3614 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3615 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3616 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3617 yCursorPosition, mPointerSimple.downTime,
3618 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003619 }
3620
3621 if (mPointerSimple.hovering && !hovering) {
3622 mPointerSimple.hovering = false;
3623
3624 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003625 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3626 mSource, displayId, policyFlags,
3627 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3628 mLastRawState.buttonState, MotionClassification::NONE,
3629 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3630 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3631 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3632 yCursorPosition, mPointerSimple.downTime,
3633 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003634 }
3635
3636 if (down) {
3637 if (!mPointerSimple.down) {
3638 mPointerSimple.down = true;
3639 mPointerSimple.downTime = when;
3640
3641 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003642 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3643 mSource, displayId, policyFlags,
3644 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3645 mCurrentRawState.buttonState, MotionClassification::NONE,
3646 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3647 &mPointerSimple.currentProperties,
3648 &mPointerSimple.currentCoords, mOrientedXPrecision,
3649 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3650 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003651 }
3652
3653 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003654 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3655 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3656 0, 0, metaState, mCurrentRawState.buttonState,
3657 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3658 &mPointerSimple.currentProperties,
3659 &mPointerSimple.currentCoords, mOrientedXPrecision,
3660 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3661 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003662 }
3663
3664 if (hovering) {
3665 if (!mPointerSimple.hovering) {
3666 mPointerSimple.hovering = true;
3667
3668 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003669 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3670 mSource, displayId, policyFlags,
3671 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3672 mCurrentRawState.buttonState, MotionClassification::NONE,
3673 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3674 &mPointerSimple.currentProperties,
3675 &mPointerSimple.currentCoords, mOrientedXPrecision,
3676 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3677 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003678 }
3679
3680 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003681 out.push_back(
3682 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3683 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3684 metaState, mCurrentRawState.buttonState,
3685 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3686 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3687 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3688 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003689 }
3690
3691 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3692 float vscroll = mCurrentRawState.rawVScroll;
3693 float hscroll = mCurrentRawState.rawHScroll;
3694 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3695 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3696
3697 // Send scroll.
3698 PointerCoords pointerCoords;
3699 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3700 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3701 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3702
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003703 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3704 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3705 0, 0, metaState, mCurrentRawState.buttonState,
3706 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3707 &mPointerSimple.currentProperties, &pointerCoords,
3708 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3709 yCursorPosition, mPointerSimple.downTime,
3710 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003711 }
3712
3713 // Save state.
3714 if (down || hovering) {
3715 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3716 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003717 mPointerSimple.displayId = displayId;
3718 mPointerSimple.source = mSource;
3719 mPointerSimple.lastCursorX = xCursorPosition;
3720 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003721 } else {
3722 mPointerSimple.reset();
3723 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003724 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003725}
3726
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003727std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3728 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003729 std::list<NotifyArgs> out;
3730 if (mPointerSimple.down || mPointerSimple.hovering) {
3731 int32_t metaState = getContext()->getGlobalMetaState();
3732 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3733 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3734 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3735 metaState, mLastRawState.buttonState,
3736 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3737 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3738 mOrientedXPrecision, mOrientedYPrecision,
3739 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3740 mPointerSimple.downTime,
3741 /* videoFrames */ {}));
3742 if (mPointerController != nullptr) {
3743 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3744 }
3745 }
3746 mPointerSimple.reset();
3747 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003748}
3749
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003750NotifyMotionArgs TouchInputMapper::dispatchMotion(
3751 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3752 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003753 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3754 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003755 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003756 PointerCoords pointerCoords[MAX_POINTERS];
3757 PointerProperties pointerProperties[MAX_POINTERS];
3758 uint32_t pointerCount = 0;
3759 while (!idBits.isEmpty()) {
3760 uint32_t id = idBits.clearFirstMarkedBit();
3761 uint32_t index = idToIndex[id];
3762 pointerProperties[pointerCount].copyFrom(properties[index]);
3763 pointerCoords[pointerCount].copyFrom(coords[index]);
3764
3765 if (changedId >= 0 && id == uint32_t(changedId)) {
3766 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3767 }
3768
3769 pointerCount += 1;
3770 }
3771
3772 ALOG_ASSERT(pointerCount != 0);
3773
3774 if (changedId >= 0 && pointerCount == 1) {
3775 // Replace initial down and final up action.
3776 // We can compare the action without masking off the changed pointer index
3777 // because we know the index is 0.
3778 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3779 action = AMOTION_EVENT_ACTION_DOWN;
3780 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003781 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3782 action = AMOTION_EVENT_ACTION_CANCEL;
3783 } else {
3784 action = AMOTION_EVENT_ACTION_UP;
3785 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003786 } else {
3787 // Can't happen.
3788 ALOG_ASSERT(false);
3789 }
3790 }
3791 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3792 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003793 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003794 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003795 }
3796 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3797 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003798 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003799 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003800 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003801 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3802 policyFlags, action, actionButton, flags, metaState, buttonState,
3803 classification, edgeFlags, pointerCount, pointerProperties,
3804 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3805 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003806}
3807
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003808std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3809 std::list<NotifyArgs> out;
3810 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3811 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3812 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003813}
3814
Prabir Pradhan1728b212021-10-19 16:00:03 -07003815// Transform input device coordinates to display panel coordinates.
3816void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003817 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3818 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3819
arthurhunga36b28e2020-12-29 20:28:15 +08003820 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3821 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3822
Prabir Pradhan1728b212021-10-19 16:00:03 -07003823 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003824 // 0 - no swap and reverse.
3825 // 90 - swap x/y and reverse y.
3826 // 180 - reverse x, y.
3827 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003828 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003829 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003830 x = xScaled;
3831 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003832 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003833 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003834 y = xScaledMax;
3835 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003836 break;
3837 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003838 x = xScaledMax;
3839 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003840 break;
3841 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003842 y = xScaled;
3843 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003844 break;
3845 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003846 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003847 }
3848}
3849
Prabir Pradhan1728b212021-10-19 16:00:03 -07003850bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003851 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3852 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3853
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003854 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003855 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00003856 isPointInRect(mPhysicalFrameInDisplay, xScaled, yScaled);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003857}
3858
3859const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3860 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003861 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3862 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3863 "left=%d, top=%d, right=%d, bottom=%d",
3864 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3865 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003866
3867 if (virtualKey.isHit(x, y)) {
3868 return &virtualKey;
3869 }
3870 }
3871
3872 return nullptr;
3873}
3874
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003875void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3876 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3877 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003878
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003879 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003880
3881 if (currentPointerCount == 0) {
3882 // No pointers to assign.
3883 return;
3884 }
3885
3886 if (lastPointerCount == 0) {
3887 // All pointers are new.
3888 for (uint32_t i = 0; i < currentPointerCount; i++) {
3889 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003890 current.rawPointerData.pointers[i].id = id;
3891 current.rawPointerData.idToIndex[id] = i;
3892 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003893 }
3894 return;
3895 }
3896
3897 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003898 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003899 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003900 uint32_t id = last.rawPointerData.pointers[0].id;
3901 current.rawPointerData.pointers[0].id = id;
3902 current.rawPointerData.idToIndex[id] = 0;
3903 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003904 return;
3905 }
3906
3907 // General case.
3908 // We build a heap of squared euclidean distances between current and last pointers
3909 // associated with the current and last pointer indices. Then, we find the best
3910 // match (by distance) for each current pointer.
3911 // The pointers must have the same tool type but it is possible for them to
3912 // transition from hovering to touching or vice-versa while retaining the same id.
3913 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3914
3915 uint32_t heapSize = 0;
3916 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3917 currentPointerIndex++) {
3918 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3919 lastPointerIndex++) {
3920 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003921 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003922 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003923 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003924 if (currentPointer.toolType == lastPointer.toolType) {
3925 int64_t deltaX = currentPointer.x - lastPointer.x;
3926 int64_t deltaY = currentPointer.y - lastPointer.y;
3927
3928 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3929
3930 // Insert new element into the heap (sift up).
3931 heap[heapSize].currentPointerIndex = currentPointerIndex;
3932 heap[heapSize].lastPointerIndex = lastPointerIndex;
3933 heap[heapSize].distance = distance;
3934 heapSize += 1;
3935 }
3936 }
3937 }
3938
3939 // Heapify
3940 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3941 startIndex -= 1;
3942 for (uint32_t parentIndex = startIndex;;) {
3943 uint32_t childIndex = parentIndex * 2 + 1;
3944 if (childIndex >= heapSize) {
3945 break;
3946 }
3947
3948 if (childIndex + 1 < heapSize &&
3949 heap[childIndex + 1].distance < heap[childIndex].distance) {
3950 childIndex += 1;
3951 }
3952
3953 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3954 break;
3955 }
3956
3957 swap(heap[parentIndex], heap[childIndex]);
3958 parentIndex = childIndex;
3959 }
3960 }
3961
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003962 if (DEBUG_POINTER_ASSIGNMENT) {
3963 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3964 for (size_t i = 0; i < heapSize; i++) {
3965 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3966 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3967 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003968 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003969
3970 // Pull matches out by increasing order of distance.
3971 // To avoid reassigning pointers that have already been matched, the loop keeps track
3972 // of which last and current pointers have been matched using the matchedXXXBits variables.
3973 // It also tracks the used pointer id bits.
3974 BitSet32 matchedLastBits(0);
3975 BitSet32 matchedCurrentBits(0);
3976 BitSet32 usedIdBits(0);
3977 bool first = true;
3978 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3979 while (heapSize > 0) {
3980 if (first) {
3981 // The first time through the loop, we just consume the root element of
3982 // the heap (the one with smallest distance).
3983 first = false;
3984 } else {
3985 // Previous iterations consumed the root element of the heap.
3986 // Pop root element off of the heap (sift down).
3987 heap[0] = heap[heapSize];
3988 for (uint32_t parentIndex = 0;;) {
3989 uint32_t childIndex = parentIndex * 2 + 1;
3990 if (childIndex >= heapSize) {
3991 break;
3992 }
3993
3994 if (childIndex + 1 < heapSize &&
3995 heap[childIndex + 1].distance < heap[childIndex].distance) {
3996 childIndex += 1;
3997 }
3998
3999 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4000 break;
4001 }
4002
4003 swap(heap[parentIndex], heap[childIndex]);
4004 parentIndex = childIndex;
4005 }
4006
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004007 if (DEBUG_POINTER_ASSIGNMENT) {
4008 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4009 for (size_t j = 0; j < heapSize; j++) {
4010 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4011 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4012 heap[j].distance);
4013 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004014 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004015 }
4016
4017 heapSize -= 1;
4018
4019 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4020 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4021
4022 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4023 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4024
4025 matchedCurrentBits.markBit(currentPointerIndex);
4026 matchedLastBits.markBit(lastPointerIndex);
4027
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004028 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4029 current.rawPointerData.pointers[currentPointerIndex].id = id;
4030 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4031 current.rawPointerData.markIdBit(id,
4032 current.rawPointerData.isHovering(
4033 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004034 usedIdBits.markBit(id);
4035
Harry Cutts45483602022-08-24 14:36:48 +00004036 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4037 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4038 ", distance=%" PRIu64,
4039 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004040 break;
4041 }
4042 }
4043
4044 // Assign fresh ids to pointers that were not matched in the process.
4045 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4046 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4047 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4048
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004049 current.rawPointerData.pointers[currentPointerIndex].id = id;
4050 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4051 current.rawPointerData.markIdBit(id,
4052 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004053
Harry Cutts45483602022-08-24 14:36:48 +00004054 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4055 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4056 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004057 }
4058}
4059
4060int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4061 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4062 return AKEY_STATE_VIRTUAL;
4063 }
4064
4065 for (const VirtualKey& virtualKey : mVirtualKeys) {
4066 if (virtualKey.keyCode == keyCode) {
4067 return AKEY_STATE_UP;
4068 }
4069 }
4070
4071 return AKEY_STATE_UNKNOWN;
4072}
4073
4074int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4075 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4076 return AKEY_STATE_VIRTUAL;
4077 }
4078
4079 for (const VirtualKey& virtualKey : mVirtualKeys) {
4080 if (virtualKey.scanCode == scanCode) {
4081 return AKEY_STATE_UP;
4082 }
4083 }
4084
4085 return AKEY_STATE_UNKNOWN;
4086}
4087
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004088bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4089 const std::vector<int32_t>& keyCodes,
4090 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004091 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004092 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004093 if (virtualKey.keyCode == keyCodes[i]) {
4094 outFlags[i] = 1;
4095 }
4096 }
4097 }
4098
4099 return true;
4100}
4101
4102std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4103 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004104 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004105 return std::make_optional(mPointerController->getDisplayId());
4106 } else {
4107 return std::make_optional(mViewport.displayId);
4108 }
4109 }
4110 return std::nullopt;
4111}
4112
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004113} // namespace android