blob: 5631a102530b19b3972b7d5890cf13d3417e4fd7 [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 Pradhan2d613f42022-11-10 20:22:06 +000083static std::tuple<ui::Size /*displayBounds*/, Rect /*physicalFrame*/> getNaturalDisplayInfo(
84 const DisplayViewport& viewport, int32_t naturalOrientation) {
85 const auto rotation = ui::toRotation(naturalOrientation);
86
87 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
88 if (rotation == ui::ROTATION_90 || rotation == ui::ROTATION_270) {
89 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
90 }
91
92 ui::Transform rotate(ui::Transform::toRotationFlags(rotation), rotatedDisplaySize.width,
93 rotatedDisplaySize.height);
94
95 Rect physicalFrame{viewport.physicalLeft, viewport.physicalTop, viewport.physicalRight,
96 viewport.physicalBottom};
97 physicalFrame = rotate.transform(physicalFrame);
98
99 LOG_ALWAYS_FATAL_IF(!physicalFrame.isValid());
100 if (physicalFrame.isEmpty()) {
101 ALOGE("Viewport is not set properly: %s", viewport.toString().c_str());
102 physicalFrame.right =
103 physicalFrame.left + (physicalFrame.width() == 0 ? 1 : physicalFrame.width());
104 physicalFrame.bottom =
105 physicalFrame.top + (physicalFrame.height() == 0 ? 1 : physicalFrame.height());
106 }
107 return {rotatedDisplaySize, physicalFrame};
108}
109
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700110// --- RawPointerData ---
111
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700112void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
113 float x = 0, y = 0;
114 uint32_t count = touchingIdBits.count();
115 if (count) {
116 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
117 uint32_t id = idBits.clearFirstMarkedBit();
118 const Pointer& pointer = pointerForId(id);
119 x += pointer.x;
120 y += pointer.y;
121 }
122 x /= count;
123 y /= count;
124 }
125 *outX = x;
126 *outY = y;
127}
128
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700129// --- TouchInputMapper ---
130
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800131TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
132 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000133 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700134 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100135 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700136 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700137
138TouchInputMapper::~TouchInputMapper() {}
139
Philip Junker4af3b3d2021-12-14 10:36:55 +0100140uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700141 return mSource;
142}
143
144void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
145 InputMapper::populateDeviceInfo(info);
146
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000147 if (mDeviceMode == DeviceMode::DISABLED) {
148 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700149 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000150
151 info->addMotionRange(mOrientedRanges.x);
152 info->addMotionRange(mOrientedRanges.y);
153 info->addMotionRange(mOrientedRanges.pressure);
154
155 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
156 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
157 //
158 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
159 // motion, i.e. the hardware dimensions, as the finger could move completely across the
160 // touchpad in one sample cycle.
161 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
162 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
163 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
164 x.resolution);
165 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
166 y.resolution);
167 }
168
169 if (mOrientedRanges.size) {
170 info->addMotionRange(*mOrientedRanges.size);
171 }
172
173 if (mOrientedRanges.touchMajor) {
174 info->addMotionRange(*mOrientedRanges.touchMajor);
175 info->addMotionRange(*mOrientedRanges.touchMinor);
176 }
177
178 if (mOrientedRanges.toolMajor) {
179 info->addMotionRange(*mOrientedRanges.toolMajor);
180 info->addMotionRange(*mOrientedRanges.toolMinor);
181 }
182
183 if (mOrientedRanges.orientation) {
184 info->addMotionRange(*mOrientedRanges.orientation);
185 }
186
187 if (mOrientedRanges.distance) {
188 info->addMotionRange(*mOrientedRanges.distance);
189 }
190
191 if (mOrientedRanges.tilt) {
192 info->addMotionRange(*mOrientedRanges.tilt);
193 }
194
195 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
196 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
197 }
198 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
199 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
200 }
201 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
202 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
203 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
204 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
205 x.resolution);
206 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
207 y.resolution);
208 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
209 x.resolution);
210 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
211 y.resolution);
212 }
213 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000214 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700215}
216
217void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700218 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800219 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700220 dumpParameters(dump);
221 dumpVirtualKeys(dump);
222 dumpRawPointerAxes(dump);
223 dumpCalibration(dump);
224 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700225 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700226
227 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700228 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
229 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
230 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
231 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
232 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
233 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
234 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
235 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
236 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
237 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
238 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
239 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
240 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
241 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
242
243 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
244 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
245 mLastRawState.rawPointerData.pointerCount);
246 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
247 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
248 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
249 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
250 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
251 "toolType=%d, isHovering=%s\n",
252 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
253 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
254 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
255 pointer.distance, pointer.toolType, toString(pointer.isHovering));
256 }
257
258 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
259 mLastCookedState.buttonState);
260 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
261 mLastCookedState.cookedPointerData.pointerCount);
262 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
263 const PointerProperties& pointerProperties =
264 mLastCookedState.cookedPointerData.pointerProperties[i];
265 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000266 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
267 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
268 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700269 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
270 "toolType=%d, isHovering=%s\n",
271 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000272 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
273 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700274 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
275 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
276 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
277 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
278 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
279 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
280 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
281 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
282 pointerProperties.toolType,
283 toString(mLastCookedState.cookedPointerData.isHovering(i)));
284 }
285
286 dump += INDENT3 "Stylus Fusion:\n";
287 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
288 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000289 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
290 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700291 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
292 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000293 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
294 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700295 dump += INDENT3 "External Stylus State:\n";
296 dumpStylusState(dump, mExternalStylusState);
297
Michael Wright227c5542020-07-02 18:30:52 +0100298 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700299 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
300 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
301 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
302 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
303 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
304 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
305 }
306}
307
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700308std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
309 const InputReaderConfiguration* config,
310 uint32_t changes) {
311 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700312
313 mConfig = *config;
314
315 if (!changes) { // first time only
316 // Configure basic parameters.
317 configureParameters();
318
319 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800320 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000321 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700322
323 // Configure absolute axis information.
324 configureRawPointerAxes();
325
326 // Prepare input device calibration.
327 parseCalibration();
328 resolveCalibration();
329 }
330
331 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
332 // Update location calibration to reflect current settings
333 updateAffineTransformation();
334 }
335
336 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
337 // Update pointer speed.
338 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
339 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
340 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
341 }
342
343 bool resetNeeded = false;
344 if (!changes ||
345 (changes &
346 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800347 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700348 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
349 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
350 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700351 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700352 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700353 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700354 }
355
356 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700357 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000358
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700359 // Send reset, unless this is the first time the device has been configured,
360 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000361 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700362 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700363 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364}
365
366void TouchInputMapper::resolveExternalStylusPresence() {
367 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800368 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700369 mExternalStylusConnected = !devices.empty();
370
371 if (!mExternalStylusConnected) {
372 resetExternalStylus();
373 }
374}
375
376void TouchInputMapper::configureParameters() {
377 // Use the pointer presentation mode for devices that do not support distinct
378 // multitouch. The spot-based presentation relies on being able to accurately
379 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800380 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100381 ? Parameters::GestureMode::SINGLE_TOUCH
382 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700383
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700384 std::string gestureModeString;
385 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800386 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700387 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100388 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100390 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700391 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700392 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700393 }
394 }
395
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800396 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700397 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100398 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800399 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700400 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100401 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 } else {
403 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100404 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700405 }
406
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800407 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700408
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700409 std::string deviceTypeString;
410 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800411 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700412 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100413 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700414 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100415 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700416 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100417 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700418 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700419 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700420 }
421 }
422
Michael Wright227c5542020-07-02 18:30:52 +0100423 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700424 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800425 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700427 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700428 std::string orientationString;
429 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700430 orientationString)) {
431 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
432 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
433 } else if (orientationString == "ORIENTATION_90") {
434 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
435 } else if (orientationString == "ORIENTATION_180") {
436 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
437 } else if (orientationString == "ORIENTATION_270") {
438 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
439 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700440 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700441 }
442 }
443
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444 mParameters.hasAssociatedDisplay = false;
445 mParameters.associatedDisplayIsExternal = false;
446 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100447 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
448 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100450 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800451 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700452 std::string uniqueDisplayId;
453 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
456 }
457 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800458 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 mParameters.hasAssociatedDisplay = true;
460 }
461
462 // Initial downs on external touch devices should wake the device.
463 // Normally we don't do this for internal touch screens to prevent them from waking
464 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800465 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700466 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000467
468 mParameters.supportsUsi = false;
469 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
470 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700471
472 mParameters.enableForInactiveViewport = false;
473 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
474 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700475}
476
477void TouchInputMapper::dumpParameters(std::string& dump) {
478 dump += INDENT3 "Parameters:\n";
479
Dominik Laskowski75788452021-02-09 18:51:25 -0800480 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481
Dominik Laskowski75788452021-02-09 18:51:25 -0800482 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700483
484 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
485 "displayId='%s'\n",
486 toString(mParameters.hasAssociatedDisplay),
487 toString(mParameters.associatedDisplayIsExternal),
488 mParameters.uniqueDisplayId.c_str());
489 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800490 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000491 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700492 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
493 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700494}
495
496void TouchInputMapper::configureRawPointerAxes() {
497 mRawPointerAxes.clear();
498}
499
500void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
501 dump += INDENT3 "Raw Touch Axes:\n";
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
510 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
511 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
512 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
513 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
514 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
515}
516
517bool TouchInputMapper::hasExternalStylus() const {
518 return mExternalStylusConnected;
519}
520
521/**
522 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000523 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800524 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000525 * 3. Get the matching viewport by either unique id in idc file or by the display type
526 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800527 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700528 */
529std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800530 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000531 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800532 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700533 }
534
Christine Franks2a2293c2022-01-18 11:51:16 -0800535 const std::optional<std::string> associatedDisplayUniqueId =
536 getDeviceContext().getAssociatedDisplayUniqueId();
537 if (associatedDisplayUniqueId) {
538 return getDeviceContext().getAssociatedViewport();
539 }
540
Michael Wright227c5542020-07-02 18:30:52 +0100541 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800542 std::optional<DisplayViewport> viewport =
543 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
544 if (viewport) {
545 return viewport;
546 } else {
547 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
548 mConfig.defaultPointerDisplayId);
549 }
550 }
551
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700552 // Check if uniqueDisplayId is specified in idc file.
553 if (!mParameters.uniqueDisplayId.empty()) {
554 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
555 }
556
557 ViewportType viewportTypeToUse;
558 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100559 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700560 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100561 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700562 }
563
564 std::optional<DisplayViewport> viewport =
565 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100566 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700567 ALOGW("Input device %s should be associated with external display, "
568 "fallback to internal one for the external viewport is not found.",
569 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100570 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700571 }
572
573 return viewport;
574 }
575
576 // No associated display, return a non-display viewport.
577 DisplayViewport newViewport;
578 // Raw width and height in the natural orientation.
579 int32_t rawWidth = mRawPointerAxes.getRawWidth();
580 int32_t rawHeight = mRawPointerAxes.getRawHeight();
581 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
582 return std::make_optional(newViewport);
583}
584
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800585int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
586 if (resolution < 0) {
587 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
588 getDeviceName().c_str());
589 return 0;
590 }
591 return resolution;
592}
593
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800594void TouchInputMapper::initializeSizeRanges() {
595 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
596 mSizeScale = 0.0f;
597 return;
598 }
599
600 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000601 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800602
603 // Size factors.
604 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
605 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
606 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
607 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
608 } else {
609 mSizeScale = 0.0f;
610 }
611
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700612 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
613 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
614 .source = mSource,
615 .min = 0,
616 .max = diagonalSize,
617 .flat = 0,
618 .fuzz = 0,
619 .resolution = 0,
620 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800621
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800622 if (mRawPointerAxes.touchMajor.valid) {
623 mRawPointerAxes.touchMajor.resolution =
624 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700625 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800626 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800627
628 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700629 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800630 if (mRawPointerAxes.touchMinor.valid) {
631 mRawPointerAxes.touchMinor.resolution =
632 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700633 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800634 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800635
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700636 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
637 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
638 .source = mSource,
639 .min = 0,
640 .max = diagonalSize,
641 .flat = 0,
642 .fuzz = 0,
643 .resolution = 0,
644 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800645 if (mRawPointerAxes.toolMajor.valid) {
646 mRawPointerAxes.toolMajor.resolution =
647 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700648 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800649 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800650
651 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700652 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800653 if (mRawPointerAxes.toolMinor.valid) {
654 mRawPointerAxes.toolMinor.resolution =
655 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700656 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800657 }
658
659 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700660 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
661 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
662 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
663 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800664 } else {
665 // Support for other calibrations can be added here.
666 ALOGW("%s calibration is not supported for size ranges at the moment. "
667 "Using raw resolution instead",
668 ftl::enum_string(mCalibration.sizeCalibration).c_str());
669 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800670
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700671 mOrientedRanges.size = InputDeviceInfo::MotionRange{
672 .axis = AMOTION_EVENT_AXIS_SIZE,
673 .source = mSource,
674 .min = 0,
675 .max = 1.0,
676 .flat = 0,
677 .fuzz = 0,
678 .resolution = 0,
679 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800680}
681
682void TouchInputMapper::initializeOrientedRanges() {
683 // Configure X and Y factors.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000684 mXScale = float(mDisplayBounds.width) / mRawPointerAxes.getRawWidth();
685 mYScale = float(mDisplayBounds.height) / mRawPointerAxes.getRawHeight();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800686 mXPrecision = 1.0f / mXScale;
687 mYPrecision = 1.0f / mYScale;
688
689 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
690 mOrientedRanges.x.source = mSource;
691 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
692 mOrientedRanges.y.source = mSource;
693
694 // Scale factor for terms that are not oriented in a particular axis.
695 // If the pixels are square then xScale == yScale otherwise we fake it
696 // by choosing an average.
697 mGeometricScale = avg(mXScale, mYScale);
698
699 initializeSizeRanges();
700
701 // Pressure factors.
702 mPressureScale = 0;
703 float pressureMax = 1.0;
704 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
705 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700706 if (mCalibration.pressureScale) {
707 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800708 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
709 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
710 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
711 }
712 }
713
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700714 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
715 .axis = AMOTION_EVENT_AXIS_PRESSURE,
716 .source = mSource,
717 .min = 0,
718 .max = pressureMax,
719 .flat = 0,
720 .fuzz = 0,
721 .resolution = 0,
722 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800723
724 // Tilt
725 mTiltXCenter = 0;
726 mTiltXScale = 0;
727 mTiltYCenter = 0;
728 mTiltYScale = 0;
729 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
730 if (mHaveTilt) {
731 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
732 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
733 mTiltXScale = M_PI / 180;
734 mTiltYScale = M_PI / 180;
735
736 if (mRawPointerAxes.tiltX.resolution) {
737 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
738 }
739 if (mRawPointerAxes.tiltY.resolution) {
740 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
741 }
742
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700743 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
744 .axis = AMOTION_EVENT_AXIS_TILT,
745 .source = mSource,
746 .min = 0,
747 .max = M_PI_2,
748 .flat = 0,
749 .fuzz = 0,
750 .resolution = 0,
751 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800752 }
753
754 // Orientation
755 mOrientationScale = 0;
756 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700757 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
758 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
759 .source = mSource,
760 .min = -M_PI,
761 .max = M_PI,
762 .flat = 0,
763 .fuzz = 0,
764 .resolution = 0,
765 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800766
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800767 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
768 if (mCalibration.orientationCalibration ==
769 Calibration::OrientationCalibration::INTERPOLATED) {
770 if (mRawPointerAxes.orientation.valid) {
771 if (mRawPointerAxes.orientation.maxValue > 0) {
772 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
773 } else if (mRawPointerAxes.orientation.minValue < 0) {
774 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
775 } else {
776 mOrientationScale = 0;
777 }
778 }
779 }
780
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700781 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
782 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
783 .source = mSource,
784 .min = -M_PI_2,
785 .max = M_PI_2,
786 .flat = 0,
787 .fuzz = 0,
788 .resolution = 0,
789 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800790 }
791
792 // Distance
793 mDistanceScale = 0;
794 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
795 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700796 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800797 }
798
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700799 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800800
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700801 .axis = AMOTION_EVENT_AXIS_DISTANCE,
802 .source = mSource,
803 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
804 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
805 .flat = 0,
806 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
807 .resolution = 0,
808 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800809 }
810
811 // Compute oriented precision, scales and ranges.
812 // Note that the maximum value reported is an inclusive maximum value so it is one
813 // unit less than the total width or height of the display.
814 switch (mInputDeviceOrientation) {
815 case DISPLAY_ORIENTATION_90:
816 case DISPLAY_ORIENTATION_270:
817 mOrientedXPrecision = mYPrecision;
818 mOrientedYPrecision = mXPrecision;
819
820 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000821 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800822 mOrientedRanges.x.flat = 0;
823 mOrientedRanges.x.fuzz = 0;
824 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
825
826 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000827 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800828 mOrientedRanges.y.flat = 0;
829 mOrientedRanges.y.fuzz = 0;
830 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
831 break;
832
833 default:
834 mOrientedXPrecision = mXPrecision;
835 mOrientedYPrecision = mYPrecision;
836
837 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000838 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800839 mOrientedRanges.x.flat = 0;
840 mOrientedRanges.x.fuzz = 0;
841 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
842
843 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000844 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800845 mOrientedRanges.y.flat = 0;
846 mOrientedRanges.y.fuzz = 0;
847 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
848 break;
849 }
850}
851
Prabir Pradhan1728b212021-10-19 16:00:03 -0700852void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000853 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700854
855 resolveExternalStylusPresence();
856
857 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100858 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000859 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700860 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100861 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700862 if (hasStylus()) {
863 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000864 } else {
865 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700866 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800867 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700868 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100869 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700870 if (hasStylus()) {
871 mSource |= AINPUT_SOURCE_STYLUS;
872 }
873 if (hasExternalStylus()) {
874 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
875 }
Michael Wright227c5542020-07-02 18:30:52 +0100876 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700877 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100878 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700879 } else {
880 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100881 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700882 }
883
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000884 const std::optional<DisplayViewport> newViewportOpt = findViewport();
885
886 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700887 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
888 ALOGW("Touch device '%s' did not report support for X or Y axis! "
889 "The device will be inoperable.",
890 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100891 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000892 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700893 ALOGI("Touch device '%s' could not query the properties of its associated "
894 "display. The device will be inoperable until the display size "
895 "becomes available.",
896 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100897 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700898 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000899 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
900 getDeviceName().c_str(), getDeviceId());
901 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000902 }
903
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000905 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000906 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
907 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
908 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
909 const float rawMeanResolution =
910 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000912 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
913 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700914 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700915 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000916 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
917 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
918 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700919
Michael Wright227c5542020-07-02 18:30:52 +0100920 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000921 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700922
Prabir Pradhan1728b212021-10-19 16:00:03 -0700923 // Apply the inverse of the input device orientation so that the input device is
924 // configured in the same orientation as the viewport. The input device orientation will
925 // be re-applied by mInputDeviceOrientation.
926 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700927 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700928
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000929 std::tie(mDisplayBounds, mPhysicalFrameInDisplay) =
930 getNaturalDisplayInfo(mViewport, naturalDeviceOrientation);
Prabir Pradhan5632d622021-09-06 07:57:20 -0700931
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000932 // InputReader works in the un-rotated display coordinate space, so we don't need to do
933 // anything if the device is already orientation-aware. If the device is not
934 // orientation-aware, then we need to apply the inverse rotation of the display so that
935 // when the display rotation is applied later as a part of the per-window transform, we
936 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700937 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000938 ? DISPLAY_ORIENTATION_0
939 : getInverseRotation(mViewport.orientation);
940 // For orientation-aware devices that work in the un-rotated coordinate space, the
941 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000942 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000943 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700944
945 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700946 mInputDeviceOrientation =
947 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700948 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000949 mDisplayBounds = rawSize;
950 mPhysicalFrameInDisplay = Rect{mDisplayBounds};
Prabir Pradhan1728b212021-10-19 16:00:03 -0700951 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700952 }
953 }
954
955 // If moving between pointer modes, need to reset some state.
956 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
957 if (deviceModeChanged) {
958 mOrientedRanges.clear();
959 }
960
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800961 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
962 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100963 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800964 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000965 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
966 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800967 if (mPointerController == nullptr) {
968 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700969 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000970 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800971 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
972 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700973 } else {
lilinnandef700b2022-06-17 19:32:01 +0800974 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
975 !mConfig.showTouches) {
976 mPointerController->clearSpots();
977 }
Michael Wright17db18e2020-06-26 20:51:44 +0100978 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700979 }
980
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700981 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000982 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700983 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000984 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700985 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700986
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700987 configureVirtualKeys();
988
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800989 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990
991 // Location
992 updateAffineTransformation();
993
Michael Wright227c5542020-07-02 18:30:52 +0100994 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700995 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000996 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
997 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700998
999 // Scale movements such that one whole swipe of the touch pad covers a
1000 // given area relative to the diagonal size of the display when no acceleration
1001 // is applied.
1002 // Assume that the touch pad has a square aspect ratio such that movements in
1003 // X and Y of the same number of raw units cover the same physical distance.
1004 mPointerXMovementScale =
1005 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1006 mPointerYMovementScale = mPointerXMovementScale;
1007
1008 // Scale zooms to cover a smaller range of the display than movements do.
1009 // This value determines the area around the pointer that is affected by freeform
1010 // pointer gestures.
1011 mPointerXZoomScale =
1012 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1013 mPointerYZoomScale = mPointerXZoomScale;
1014
HQ Liue6983c72022-04-19 22:14:56 +00001015 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1016 // axis is non positive value.
1017 const float minFreeformGestureWidth =
1018 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1019
1020 mPointerGestureMaxSwipeWidth =
1021 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1022 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023 }
1024
1025 // Inform the dispatcher about the changes.
1026 *outResetNeeded = true;
1027 bumpGeneration();
1028 }
1029}
1030
Prabir Pradhan1728b212021-10-19 16:00:03 -07001031void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001033 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
1034 dump += StringPrintf(INDENT3 "PhysicalFrame: %s\n", toString(mPhysicalFrameInDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001035 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001036}
1037
1038void TouchInputMapper::configureVirtualKeys() {
1039 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001040 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001041
1042 mVirtualKeys.clear();
1043
1044 if (virtualKeyDefinitions.size() == 0) {
1045 return;
1046 }
1047
1048 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1049 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1050 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1051 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1052
1053 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1054 VirtualKey virtualKey;
1055
1056 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1057 int32_t keyCode;
1058 int32_t dummyKeyMetaState;
1059 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001060 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1061 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1063 continue; // drop the key
1064 }
1065
1066 virtualKey.keyCode = keyCode;
1067 virtualKey.flags = flags;
1068
1069 // convert the key definition's display coordinates into touch coordinates for a hit box
1070 int32_t halfWidth = virtualKeyDefinition.width / 2;
1071 int32_t halfHeight = virtualKeyDefinition.height / 2;
1072
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001073 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1074 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001075 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001076 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1077 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001078 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001079 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1080 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001081 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001082 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1083 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001084 touchScreenTop;
1085 mVirtualKeys.push_back(virtualKey);
1086 }
1087}
1088
1089void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1090 if (!mVirtualKeys.empty()) {
1091 dump += INDENT3 "Virtual Keys:\n";
1092
1093 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1094 const VirtualKey& virtualKey = mVirtualKeys[i];
1095 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1096 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1097 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1098 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1099 }
1100 }
1101}
1102
1103void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001104 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105 Calibration& out = mCalibration;
1106
1107 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001108 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001109 std::string sizeCalibrationString;
1110 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001112 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001114 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001115 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001116 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001118 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001119 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001120 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001121 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001122 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 }
1124 }
1125
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001126 float sizeScale;
1127
1128 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1129 out.sizeScale = sizeScale;
1130 }
1131 float sizeBias;
1132 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1133 out.sizeBias = sizeBias;
1134 }
1135 bool sizeIsSummed;
1136 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1137 out.sizeIsSummed = sizeIsSummed;
1138 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139
1140 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001141 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001142 std::string pressureCalibrationString;
1143 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001145 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001147 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001149 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 } else if (pressureCalibrationString != "default") {
1151 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001152 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001153 }
1154 }
1155
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001156 float pressureScale;
1157 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1158 out.pressureScale = pressureScale;
1159 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160
1161 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001163 std::string orientationCalibrationString;
1164 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 } else if (orientationCalibrationString != "default") {
1172 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001173 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 }
1175 }
1176
1177 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001178 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001179 std::string distanceCalibrationString;
1180 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001182 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001185 } else if (distanceCalibrationString != "default") {
1186 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001187 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 }
1189 }
1190
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001191 float distanceScale;
1192 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1193 out.distanceScale = distanceScale;
1194 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001197 std::string coverageCalibrationString;
1198 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 } else if (coverageCalibrationString != "default") {
1204 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001205 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001206 }
1207 }
1208}
1209
1210void TouchInputMapper::resolveCalibration() {
1211 // Size
1212 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001213 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1214 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 }
1216 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001217 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001218 }
1219
1220 // Pressure
1221 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001222 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1223 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 }
1225 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001226 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 }
1228
1229 // Orientation
1230 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001231 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1232 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 }
1234 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001235 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 }
1237
1238 // Distance
1239 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001240 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1241 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 }
1243 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001244 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 }
1246
1247 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001248 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1249 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251}
1252
1253void TouchInputMapper::dumpCalibration(std::string& dump) {
1254 dump += INDENT3 "Calibration:\n";
1255
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001256 dump += INDENT4 "touch.size.calibration: ";
1257 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001259 if (mCalibration.sizeScale) {
1260 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 }
1262
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001263 if (mCalibration.sizeBias) {
1264 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 }
1266
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001267 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001269 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270 }
1271
1272 // Pressure
1273 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001274 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 dump += INDENT4 "touch.pressure.calibration: none\n";
1276 break;
Michael Wright227c5542020-07-02 18:30:52 +01001277 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 dump += INDENT4 "touch.pressure.calibration: physical\n";
1279 break;
Michael Wright227c5542020-07-02 18:30:52 +01001280 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1282 break;
1283 default:
1284 ALOG_ASSERT(false);
1285 }
1286
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001287 if (mCalibration.pressureScale) {
1288 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 }
1290
1291 // Orientation
1292 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001293 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 dump += INDENT4 "touch.orientation.calibration: none\n";
1295 break;
Michael Wright227c5542020-07-02 18:30:52 +01001296 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1298 break;
Michael Wright227c5542020-07-02 18:30:52 +01001299 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 dump += INDENT4 "touch.orientation.calibration: vector\n";
1301 break;
1302 default:
1303 ALOG_ASSERT(false);
1304 }
1305
1306 // Distance
1307 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001308 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 dump += INDENT4 "touch.distance.calibration: none\n";
1310 break;
Michael Wright227c5542020-07-02 18:30:52 +01001311 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.distance.calibration: scaled\n";
1313 break;
1314 default:
1315 ALOG_ASSERT(false);
1316 }
1317
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001318 if (mCalibration.distanceScale) {
1319 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 }
1321
1322 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001323 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 dump += INDENT4 "touch.coverage.calibration: none\n";
1325 break;
Michael Wright227c5542020-07-02 18:30:52 +01001326 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001327 dump += INDENT4 "touch.coverage.calibration: box\n";
1328 break;
1329 default:
1330 ALOG_ASSERT(false);
1331 }
1332}
1333
1334void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1335 dump += INDENT3 "Affine Transformation:\n";
1336
1337 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1338 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1339 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1340 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1341 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1342 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1343}
1344
1345void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001346 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001347 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001348}
1349
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001350std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001351 std::list<NotifyArgs> out = cancelTouch(when, when);
1352 updateTouchSpots();
1353
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001354 mCursorButtonAccumulator.reset(getDeviceContext());
1355 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001356 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357
1358 mPointerVelocityControl.reset();
1359 mWheelXVelocityControl.reset();
1360 mWheelYVelocityControl.reset();
1361
1362 mRawStatesPending.clear();
1363 mCurrentRawState.clear();
1364 mCurrentCookedState.clear();
1365 mLastRawState.clear();
1366 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001367 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001368 mSentHoverEnter = false;
1369 mHavePointerIds = false;
1370 mCurrentMotionAborted = false;
1371 mDownTime = 0;
1372
1373 mCurrentVirtualKey.down = false;
1374
1375 mPointerGesture.reset();
1376 mPointerSimple.reset();
1377 resetExternalStylus();
1378
1379 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001380 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001381 mPointerController->clearSpots();
1382 }
1383
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001384 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001385}
1386
1387void TouchInputMapper::resetExternalStylus() {
1388 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001389 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001390 mExternalStylusFusionTimeout = LLONG_MAX;
1391 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001392 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001393}
1394
1395void TouchInputMapper::clearStylusDataPendingFlags() {
1396 mExternalStylusDataPending = false;
1397 mExternalStylusFusionTimeout = LLONG_MAX;
1398}
1399
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001400std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001401 mCursorButtonAccumulator.process(rawEvent);
1402 mCursorScrollAccumulator.process(rawEvent);
1403 mTouchButtonAccumulator.process(rawEvent);
1404
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001405 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001406 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001407 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001408 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001409 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410}
1411
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001412std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1413 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001414 if (mDeviceMode == DeviceMode::DISABLED) {
1415 // Only save the last pending state when the device is disabled.
1416 mRawStatesPending.clear();
1417 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001418 // Push a new state.
1419 mRawStatesPending.emplace_back();
1420
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001421 RawState& next = mRawStatesPending.back();
1422 next.clear();
1423 next.when = when;
1424 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001425
1426 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001427 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001428 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1429
1430 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001431 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1432 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001433 mCursorScrollAccumulator.finishSync();
1434
1435 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001436 syncTouch(when, &next);
1437
1438 // The last RawState is the actually second to last, since we just added a new state
1439 const RawState& last =
1440 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001441
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001442 std::tie(next.when, next.readTime) =
1443 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1444 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001445
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446 // Assign pointer ids.
1447 if (!mHavePointerIds) {
1448 assignPointerIds(last, next);
1449 }
1450
Harry Cutts45483602022-08-24 14:36:48 +00001451 ALOGD_IF(DEBUG_RAW_EVENTS,
1452 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1453 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1454 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1455 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1456 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1457 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001458
Arthur Hung9ad18942021-06-19 02:04:46 +00001459 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1460 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1461 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1462 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1463 next.rawPointerData.hoveringIdBits.value);
1464 }
1465
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001466 out += processRawTouches(false /*timeout*/);
1467 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001468}
1469
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001470std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1471 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001472 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001473 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001474 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001475 }
1476
1477 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1478 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1479 // touching the current state will only observe the events that have been dispatched to the
1480 // rest of the pipeline.
1481 const size_t N = mRawStatesPending.size();
1482 size_t count;
1483 for (count = 0; count < N; count++) {
1484 const RawState& next = mRawStatesPending[count];
1485
1486 // A failure to assign the stylus id means that we're waiting on stylus data
1487 // and so should defer the rest of the pipeline.
1488 if (assignExternalStylusId(next, timeout)) {
1489 break;
1490 }
1491
1492 // All ready to go.
1493 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001494 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001495 if (mCurrentRawState.when < mLastRawState.when) {
1496 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001497 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001499 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001500 }
1501 if (count != 0) {
1502 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1503 }
1504
1505 if (mExternalStylusDataPending) {
1506 if (timeout) {
1507 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1508 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001509 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001510 ALOGD_IF(DEBUG_STYLUS_FUSION,
1511 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001512 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001513 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001514 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1515 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1516 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1517 }
1518 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001519 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001520}
1521
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001522std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1523 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 // Always start with a clean state.
1525 mCurrentCookedState.clear();
1526
1527 // Apply stylus buttons to current raw state.
1528 applyExternalStylusButtonState(when);
1529
1530 // Handle policy on initial down or hover events.
1531 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1532 mCurrentRawState.rawPointerData.pointerCount != 0;
1533
1534 uint32_t policyFlags = 0;
1535 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1536 if (initialDown || buttonsPressed) {
1537 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001538 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001539 getContext()->fadePointer();
1540 }
1541
1542 if (mParameters.wake) {
1543 policyFlags |= POLICY_FLAG_WAKE;
1544 }
1545 }
1546
1547 // Consume raw off-screen touches before cooking pointer data.
1548 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001549 bool consumed;
1550 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1551 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001552 mCurrentRawState.rawPointerData.clear();
1553 }
1554
1555 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1556 // with cooked pointer data that has the same ids and indices as the raw data.
1557 // The following code can use either the raw or cooked data, as needed.
1558 cookPointerData();
1559
1560 // Apply stylus pressure to current cooked state.
1561 applyExternalStylusTouchState(when);
1562
1563 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001564 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1565 mSource, mViewport.displayId, policyFlags,
1566 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001567
1568 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001569 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001570 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1571 uint32_t id = idBits.clearFirstMarkedBit();
1572 const RawPointerData::Pointer& pointer =
1573 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001574 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001575 mCurrentCookedState.stylusIdBits.markBit(id);
1576 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1577 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1578 mCurrentCookedState.fingerIdBits.markBit(id);
1579 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1580 mCurrentCookedState.mouseIdBits.markBit(id);
1581 }
1582 }
1583 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1584 uint32_t id = idBits.clearFirstMarkedBit();
1585 const RawPointerData::Pointer& pointer =
1586 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001587 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001588 mCurrentCookedState.stylusIdBits.markBit(id);
1589 }
1590 }
1591
1592 // Stylus takes precedence over all tools, then mouse, then finger.
1593 PointerUsage pointerUsage = mPointerUsage;
1594 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1595 mCurrentCookedState.mouseIdBits.clear();
1596 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001597 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001598 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1599 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001600 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001601 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1602 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001603 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001604 }
1605
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001606 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001607 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001608 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001609 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001610 out += dispatchButtonRelease(when, readTime, policyFlags);
1611 out += dispatchHoverExit(when, readTime, policyFlags);
1612 out += dispatchTouches(when, readTime, policyFlags);
1613 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1614 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 }
1616
1617 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1618 mCurrentMotionAborted = false;
1619 }
1620 }
1621
1622 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001623 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1624 mSource, mViewport.displayId, policyFlags,
1625 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626
1627 // Clear some transient state.
1628 mCurrentRawState.rawVScroll = 0;
1629 mCurrentRawState.rawHScroll = 0;
1630
1631 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001632 mLastRawState = mCurrentRawState;
1633 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001634 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001635}
1636
Garfield Tanc734e4f2021-01-15 20:01:39 -08001637void TouchInputMapper::updateTouchSpots() {
1638 if (!mConfig.showTouches || mPointerController == nullptr) {
1639 return;
1640 }
1641
1642 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1643 // clear touch spots.
1644 if (mDeviceMode != DeviceMode::DIRECT &&
1645 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1646 return;
1647 }
1648
1649 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1650 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1651
1652 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001653 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1654 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001655 mCurrentCookedState.cookedPointerData.touchingIdBits,
1656 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001657}
1658
1659bool TouchInputMapper::isTouchScreen() {
1660 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1661 mParameters.hasAssociatedDisplay;
1662}
1663
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001664void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001665 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1666 // If any of the external buttons are already pressed by the touch device, ignore them.
1667 const int32_t pressedButtons = ~mCurrentRawState.buttonState & mExternalStylusState.buttons;
1668 const int32_t releasedButtons =
1669 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1670
1671 mCurrentRawState.buttonState |= pressedButtons;
1672 mCurrentRawState.buttonState &= ~releasedButtons;
1673
1674 mExternalStylusButtonsApplied |= pressedButtons;
1675 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001676 }
1677}
1678
1679void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1680 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1681 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001682 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1683 return;
1684 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001685
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001686 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1687 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1688 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1689 : 0.f;
1690 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1691 pressure = *mExternalStylusState.pressure;
1692 }
1693 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1694 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001695
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001696 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001697 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001698 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001699 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001700 }
1701}
1702
1703bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001704 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001705 return false;
1706 }
1707
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001708 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001709 if (mFusedStylusPointerId &&
1710 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001711 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001712 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001713 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714 }
1715
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001716 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1717 state.rawPointerData.pointerCount != 0;
1718 if (!initialDown) {
1719 return false;
1720 }
1721
1722 if (!mExternalStylusState.pressure) {
1723 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1724 return false;
1725 }
1726
1727 if (*mExternalStylusState.pressure != 0.0f) {
1728 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1729 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1730 return false;
1731 }
1732
1733 if (timeout) {
1734 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1735 mFusedStylusPointerId.reset();
1736 mExternalStylusFusionTimeout = LLONG_MAX;
1737 return false;
1738 }
1739
1740 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1741 // being processed until we either get pressure data or timeout.
1742 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1743 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1744 }
1745 ALOGD_IF(DEBUG_STYLUS_FUSION,
1746 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1747 mExternalStylusFusionTimeout);
1748 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1749 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001750}
1751
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001752std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1753 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001754 if (mDeviceMode == DeviceMode::POINTER) {
1755 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001756 // Since this is a synthetic event, we can consider its latency to be zero
1757 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001758 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001759 }
Michael Wright227c5542020-07-02 18:30:52 +01001760 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001761 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001762 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001763 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1764 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1765 }
1766 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001767 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001768}
1769
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001770std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1771 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001772 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001773 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001774 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001775 // The following three cases are handled here:
1776 // - We're in the middle of a fused stream of data;
1777 // - We're waiting on external stylus data before dispatching the initial down; or
1778 // - Only the button state, which is not reported through a specific pointer, has changed.
1779 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001781 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001782 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001783 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001784}
1785
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001786std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1787 uint32_t policyFlags, bool& outConsumed) {
1788 outConsumed = false;
1789 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001790 // Check for release of a virtual key.
1791 if (mCurrentVirtualKey.down) {
1792 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1793 // Pointer went up while virtual key was down.
1794 mCurrentVirtualKey.down = false;
1795 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001796 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1797 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1798 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001799 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1800 AKEY_EVENT_FLAG_FROM_SYSTEM |
1801 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001802 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001803 outConsumed = true;
1804 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001805 }
1806
1807 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1808 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1809 const RawPointerData::Pointer& pointer =
1810 mCurrentRawState.rawPointerData.pointerForId(id);
1811 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1812 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1813 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001814 outConsumed = true;
1815 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001816 }
1817 }
1818
1819 // Pointer left virtual key area or another pointer also went down.
1820 // Send key cancellation but do not consume the touch yet.
1821 // This is useful when the user swipes through from the virtual key area
1822 // into the main display surface.
1823 mCurrentVirtualKey.down = false;
1824 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001825 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1826 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001827 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1828 AKEY_EVENT_FLAG_FROM_SYSTEM |
1829 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1830 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001831 }
1832 }
1833
1834 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1835 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1836 // Pointer just went down. Check for virtual key press or off-screen touches.
1837 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1838 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001839 // Skip checking whether the pointer is inside the physical frame if the device is in
1840 // unscaled mode.
1841 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1842 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001843 // If exactly one pointer went down, check for virtual key hit.
1844 // Otherwise we will drop the entire stroke.
1845 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1846 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1847 if (virtualKey) {
1848 mCurrentVirtualKey.down = true;
1849 mCurrentVirtualKey.downTime = when;
1850 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1851 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1852 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001853 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1854 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001855
1856 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001857 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1858 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1859 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001860 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1861 AKEY_EVENT_ACTION_DOWN,
1862 AKEY_EVENT_FLAG_FROM_SYSTEM |
1863 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001864 }
1865 }
1866 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001867 outConsumed = true;
1868 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001869 }
1870 }
1871
1872 // Disable all virtual key touches that happen within a short time interval of the
1873 // most recent touch within the screen area. The idea is to filter out stray
1874 // virtual key presses when interacting with the touch screen.
1875 //
1876 // Problems we're trying to solve:
1877 //
1878 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1879 // virtual key area that is implemented by a separate touch panel and accidentally
1880 // triggers a virtual key.
1881 //
1882 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1883 // area and accidentally triggers a virtual key. This often happens when virtual keys
1884 // are layed out below the screen near to where the on screen keyboard's space bar
1885 // is displayed.
1886 if (mConfig.virtualKeyQuietTime > 0 &&
1887 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001888 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001889 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001890 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001891}
1892
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001893NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1894 uint32_t policyFlags, int32_t keyEventAction,
1895 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001896 int32_t keyCode = mCurrentVirtualKey.keyCode;
1897 int32_t scanCode = mCurrentVirtualKey.scanCode;
1898 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001899 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001900 policyFlags |= POLICY_FLAG_VIRTUAL;
1901
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001902 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1903 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1904 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001905}
1906
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001907std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1908 uint32_t policyFlags) {
1909 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001910 if (mCurrentMotionAborted) {
1911 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001912 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001913 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001914 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1915 if (!currentIdBits.isEmpty()) {
1916 int32_t metaState = getContext()->getGlobalMetaState();
1917 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001918 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001919 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1920 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001921 mCurrentCookedState.cookedPointerData.pointerProperties,
1922 mCurrentCookedState.cookedPointerData.pointerCoords,
1923 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1924 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1925 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926 mCurrentMotionAborted = true;
1927 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001928 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001929}
1930
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001931// Updates pointer coords and properties for pointers with specified ids that have moved.
1932// Returns true if any of them changed.
1933static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1934 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1935 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1936 BitSet32 idBits) {
1937 bool changed = false;
1938 while (!idBits.isEmpty()) {
1939 uint32_t id = idBits.clearFirstMarkedBit();
1940 uint32_t inIndex = inIdToIndex[id];
1941 uint32_t outIndex = outIdToIndex[id];
1942
1943 const PointerProperties& curInProperties = inProperties[inIndex];
1944 const PointerCoords& curInCoords = inCoords[inIndex];
1945 PointerProperties& curOutProperties = outProperties[outIndex];
1946 PointerCoords& curOutCoords = outCoords[outIndex];
1947
1948 if (curInProperties != curOutProperties) {
1949 curOutProperties.copyFrom(curInProperties);
1950 changed = true;
1951 }
1952
1953 if (curInCoords != curOutCoords) {
1954 curOutCoords.copyFrom(curInCoords);
1955 changed = true;
1956 }
1957 }
1958 return changed;
1959}
1960
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001961std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1962 uint32_t policyFlags) {
1963 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001964 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1965 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1966 int32_t metaState = getContext()->getGlobalMetaState();
1967 int32_t buttonState = mCurrentCookedState.buttonState;
1968
1969 if (currentIdBits == lastIdBits) {
1970 if (!currentIdBits.isEmpty()) {
1971 // No pointer id changes so this is a move event.
1972 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001973 out.push_back(
1974 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1975 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1976 mCurrentCookedState.cookedPointerData.pointerProperties,
1977 mCurrentCookedState.cookedPointerData.pointerCoords,
1978 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1979 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1980 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001981 }
1982 } else {
1983 // There may be pointers going up and pointers going down and pointers moving
1984 // all at the same time.
1985 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1986 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1987 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1988 BitSet32 dispatchedIdBits(lastIdBits.value);
1989
1990 // Update last coordinates of pointers that have moved so that we observe the new
1991 // pointer positions at the same time as other pointers that have just gone up.
1992 bool moveNeeded =
1993 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1994 mCurrentCookedState.cookedPointerData.pointerCoords,
1995 mCurrentCookedState.cookedPointerData.idToIndex,
1996 mLastCookedState.cookedPointerData.pointerProperties,
1997 mLastCookedState.cookedPointerData.pointerCoords,
1998 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1999 if (buttonState != mLastCookedState.buttonState) {
2000 moveNeeded = true;
2001 }
2002
2003 // Dispatch pointer up events.
2004 while (!upIdBits.isEmpty()) {
2005 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002006 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002007 if (isCanceled) {
2008 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2009 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002010 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2011 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2012 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2013 buttonState, 0,
2014 mLastCookedState.cookedPointerData.pointerProperties,
2015 mLastCookedState.cookedPointerData.pointerCoords,
2016 mLastCookedState.cookedPointerData.idToIndex,
2017 dispatchedIdBits, upId, mOrientedXPrecision,
2018 mOrientedYPrecision, mDownTime,
2019 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002020 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002021 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002022 }
2023
2024 // Dispatch move events if any of the remaining pointers moved from their old locations.
2025 // Although applications receive new locations as part of individual pointer up
2026 // events, they do not generally handle them except when presented in a move event.
2027 if (moveNeeded && !moveIdBits.isEmpty()) {
2028 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002029 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2030 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2031 mCurrentCookedState.cookedPointerData.pointerProperties,
2032 mCurrentCookedState.cookedPointerData.pointerCoords,
2033 mCurrentCookedState.cookedPointerData.idToIndex,
2034 dispatchedIdBits, -1, mOrientedXPrecision,
2035 mOrientedYPrecision, mDownTime,
2036 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002037 }
2038
2039 // Dispatch pointer down events using the new pointer locations.
2040 while (!downIdBits.isEmpty()) {
2041 uint32_t downId = downIdBits.clearFirstMarkedBit();
2042 dispatchedIdBits.markBit(downId);
2043
2044 if (dispatchedIdBits.count() == 1) {
2045 // First pointer is going down. Set down time.
2046 mDownTime = when;
2047 }
2048
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002049 out.push_back(
2050 dispatchMotion(when, readTime, policyFlags, mSource,
2051 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2052 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2053 mCurrentCookedState.cookedPointerData.pointerCoords,
2054 mCurrentCookedState.cookedPointerData.idToIndex,
2055 dispatchedIdBits, downId, mOrientedXPrecision,
2056 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002057 }
2058 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002059 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002060}
2061
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002062std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2063 uint32_t policyFlags) {
2064 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002065 if (mSentHoverEnter &&
2066 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2067 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2068 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002069 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2070 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2071 mLastCookedState.buttonState, 0,
2072 mLastCookedState.cookedPointerData.pointerProperties,
2073 mLastCookedState.cookedPointerData.pointerCoords,
2074 mLastCookedState.cookedPointerData.idToIndex,
2075 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2076 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2077 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002078 mSentHoverEnter = false;
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::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2084 uint32_t policyFlags) {
2085 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002086 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2087 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2088 int32_t metaState = getContext()->getGlobalMetaState();
2089 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002090 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2091 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2092 mCurrentRawState.buttonState, 0,
2093 mCurrentCookedState.cookedPointerData.pointerProperties,
2094 mCurrentCookedState.cookedPointerData.pointerCoords,
2095 mCurrentCookedState.cookedPointerData.idToIndex,
2096 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2097 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2098 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002099 mSentHoverEnter = true;
2100 }
2101
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002102 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2103 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2104 mCurrentRawState.buttonState, 0,
2105 mCurrentCookedState.cookedPointerData.pointerProperties,
2106 mCurrentCookedState.cookedPointerData.pointerCoords,
2107 mCurrentCookedState.cookedPointerData.idToIndex,
2108 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2109 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2110 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002112 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113}
2114
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002115std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2116 uint32_t policyFlags) {
2117 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002118 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2119 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2120 const int32_t metaState = getContext()->getGlobalMetaState();
2121 int32_t buttonState = mLastCookedState.buttonState;
2122 while (!releasedButtons.isEmpty()) {
2123 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2124 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002125 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2126 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2127 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002128 mLastCookedState.cookedPointerData.pointerProperties,
2129 mLastCookedState.cookedPointerData.pointerCoords,
2130 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002131 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2132 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002133 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002134 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002135}
2136
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002137std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2138 uint32_t policyFlags) {
2139 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002140 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2141 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2142 const int32_t metaState = getContext()->getGlobalMetaState();
2143 int32_t buttonState = mLastCookedState.buttonState;
2144 while (!pressedButtons.isEmpty()) {
2145 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2146 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002147 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2148 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2149 buttonState, 0,
2150 mCurrentCookedState.cookedPointerData.pointerProperties,
2151 mCurrentCookedState.cookedPointerData.pointerCoords,
2152 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2153 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2154 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002155 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002156 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157}
2158
2159const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2160 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2161 return cookedPointerData.touchingIdBits;
2162 }
2163 return cookedPointerData.hoveringIdBits;
2164}
2165
2166void TouchInputMapper::cookPointerData() {
2167 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2168
2169 mCurrentCookedState.cookedPointerData.clear();
2170 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2171 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2172 mCurrentRawState.rawPointerData.hoveringIdBits;
2173 mCurrentCookedState.cookedPointerData.touchingIdBits =
2174 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002175 mCurrentCookedState.cookedPointerData.canceledIdBits =
2176 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002177
2178 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2179 mCurrentCookedState.buttonState = 0;
2180 } else {
2181 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2182 }
2183
2184 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002185 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002186 for (uint32_t i = 0; i < currentPointerCount; i++) {
2187 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2188
2189 // Size
2190 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2191 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002192 case Calibration::SizeCalibration::GEOMETRIC:
2193 case Calibration::SizeCalibration::DIAMETER:
2194 case Calibration::SizeCalibration::BOX:
2195 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002196 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2197 touchMajor = in.touchMajor;
2198 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2199 toolMajor = in.toolMajor;
2200 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2201 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2202 : in.touchMajor;
2203 } else if (mRawPointerAxes.touchMajor.valid) {
2204 toolMajor = touchMajor = in.touchMajor;
2205 toolMinor = touchMinor =
2206 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2207 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2208 : in.touchMajor;
2209 } else if (mRawPointerAxes.toolMajor.valid) {
2210 touchMajor = toolMajor = in.toolMajor;
2211 touchMinor = toolMinor =
2212 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2213 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2214 : in.toolMajor;
2215 } else {
2216 ALOG_ASSERT(false,
2217 "No touch or tool axes. "
2218 "Size calibration should have been resolved to NONE.");
2219 touchMajor = 0;
2220 touchMinor = 0;
2221 toolMajor = 0;
2222 toolMinor = 0;
2223 size = 0;
2224 }
2225
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002226 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002227 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2228 if (touchingCount > 1) {
2229 touchMajor /= touchingCount;
2230 touchMinor /= touchingCount;
2231 toolMajor /= touchingCount;
2232 toolMinor /= touchingCount;
2233 size /= touchingCount;
2234 }
2235 }
2236
Michael Wright227c5542020-07-02 18:30:52 +01002237 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002238 touchMajor *= mGeometricScale;
2239 touchMinor *= mGeometricScale;
2240 toolMajor *= mGeometricScale;
2241 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002242 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002243 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2244 touchMinor = touchMajor;
2245 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2246 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002247 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002248 touchMinor = touchMajor;
2249 toolMinor = toolMajor;
2250 }
2251
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002252 mCalibration.applySizeScaleAndBias(touchMajor);
2253 mCalibration.applySizeScaleAndBias(touchMinor);
2254 mCalibration.applySizeScaleAndBias(toolMajor);
2255 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 size *= mSizeScale;
2257 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002258 case Calibration::SizeCalibration::DEFAULT:
2259 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2260 break;
2261 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002262 touchMajor = 0;
2263 touchMinor = 0;
2264 toolMajor = 0;
2265 toolMinor = 0;
2266 size = 0;
2267 break;
2268 }
2269
2270 // Pressure
2271 float pressure;
2272 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002273 case Calibration::PressureCalibration::PHYSICAL:
2274 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002275 pressure = in.pressure * mPressureScale;
2276 break;
2277 default:
2278 pressure = in.isHovering ? 0 : 1;
2279 break;
2280 }
2281
2282 // Tilt and Orientation
2283 float tilt;
2284 float orientation;
2285 if (mHaveTilt) {
2286 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2287 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2288 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2289 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2290 } else {
2291 tilt = 0;
2292
2293 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002294 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002295 orientation = in.orientation * mOrientationScale;
2296 break;
Michael Wright227c5542020-07-02 18:30:52 +01002297 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002298 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2299 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2300 if (c1 != 0 || c2 != 0) {
2301 orientation = atan2f(c1, c2) * 0.5f;
2302 float confidence = hypotf(c1, c2);
2303 float scale = 1.0f + confidence / 16.0f;
2304 touchMajor *= scale;
2305 touchMinor /= scale;
2306 toolMajor *= scale;
2307 toolMinor /= scale;
2308 } else {
2309 orientation = 0;
2310 }
2311 break;
2312 }
2313 default:
2314 orientation = 0;
2315 }
2316 }
2317
2318 // Distance
2319 float distance;
2320 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002321 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002322 distance = in.distance * mDistanceScale;
2323 break;
2324 default:
2325 distance = 0;
2326 }
2327
2328 // Coverage
2329 int32_t rawLeft, rawTop, rawRight, rawBottom;
2330 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002331 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2333 rawRight = in.toolMinor & 0x0000ffff;
2334 rawBottom = in.toolMajor & 0x0000ffff;
2335 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2336 break;
2337 default:
2338 rawLeft = rawTop = rawRight = rawBottom = 0;
2339 break;
2340 }
2341
2342 // Adjust X,Y coords for device calibration
2343 // TODO: Adjust coverage coords?
2344 float xTransformed = in.x, yTransformed = in.y;
2345 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002346 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347
Prabir Pradhan1728b212021-10-19 16:00:03 -07002348 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 float left, top, right, bottom;
2350
Prabir Pradhan1728b212021-10-19 16:00:03 -07002351 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002353 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2354 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2355 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2356 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002357 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002358 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002360 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 }
2362 break;
2363 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002364 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2365 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002366 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2367 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002369 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002371 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 }
2373 break;
2374 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2376 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002377 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2378 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002380 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002382 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 }
2384 break;
2385 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002386 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2387 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2388 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2389 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 break;
2391 }
2392
2393 // Write output coords.
2394 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2395 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002396 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2397 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2400 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2402 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2403 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2404 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002405 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2407 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2408 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2409 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2410 } else {
2411 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2412 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2413 }
2414
Chris Ye364fdb52020-08-05 15:07:56 -07002415 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002416 uint32_t id = in.id;
2417 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2418 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2419 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2420 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2421 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2422 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2423 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2424 }
2425
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 // Write output properties.
2427 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002428 properties.clear();
2429 properties.id = id;
2430 properties.toolType = in.toolType;
2431
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002432 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002433 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002434 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002435 }
2436}
2437
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002438std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2439 uint32_t policyFlags,
2440 PointerUsage pointerUsage) {
2441 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002443 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002444 mPointerUsage = pointerUsage;
2445 }
2446
2447 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002448 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002449 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 break;
Michael Wright227c5542020-07-02 18:30:52 +01002451 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002452 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453 break;
Michael Wright227c5542020-07-02 18:30:52 +01002454 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002455 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 break;
Michael Wright227c5542020-07-02 18:30:52 +01002457 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 break;
2459 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002460 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461}
2462
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002463std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2464 uint32_t policyFlags) {
2465 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002467 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002468 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 break;
Michael Wright227c5542020-07-02 18:30:52 +01002470 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002471 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 break;
Michael Wright227c5542020-07-02 18:30:52 +01002473 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002474 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 break;
Michael Wright227c5542020-07-02 18:30:52 +01002476 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002477 break;
2478 }
2479
Michael Wright227c5542020-07-02 18:30:52 +01002480 mPointerUsage = PointerUsage::NONE;
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::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2485 uint32_t policyFlags,
2486 bool isTimeout) {
2487 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002488 // Update current gesture coordinates.
2489 bool cancelPreviousGesture, finishPreviousGesture;
2490 bool sendEvents =
2491 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2492 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002493 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 }
2495 if (finishPreviousGesture) {
2496 cancelPreviousGesture = false;
2497 }
2498
2499 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002500 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002501 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 if (finishPreviousGesture || cancelPreviousGesture) {
2503 mPointerController->clearSpots();
2504 }
2505
Michael Wright227c5542020-07-02 18:30:52 +01002506 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002507 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2508 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002509 mPointerGesture.currentGestureIdBits,
2510 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 }
2512 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002513 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 }
2515
2516 // Show or hide the pointer if needed.
2517 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002518 case PointerGesture::Mode::NEUTRAL:
2519 case PointerGesture::Mode::QUIET:
2520 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2521 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002523 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 }
2525 break;
Michael Wright227c5542020-07-02 18:30:52 +01002526 case PointerGesture::Mode::TAP:
2527 case PointerGesture::Mode::TAP_DRAG:
2528 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2529 case PointerGesture::Mode::HOVER:
2530 case PointerGesture::Mode::PRESS:
2531 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002532 // Unfade the pointer when the current gesture manipulates the
2533 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002534 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535 break;
Michael Wright227c5542020-07-02 18:30:52 +01002536 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002537 // Fade the pointer when the current gesture manipulates a different
2538 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002539 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002540 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002542 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002543 }
2544 break;
2545 }
2546
2547 // Send events!
2548 int32_t metaState = getContext()->getGlobalMetaState();
2549 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002550 const MotionClassification classification =
2551 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2552 ? MotionClassification::TWO_FINGER_SWIPE
2553 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002554
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002555 uint32_t flags = 0;
2556
2557 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2558 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2559 }
2560
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002561 // Update last coordinates of pointers that have moved so that we observe the new
2562 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002563 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2564 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2565 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2566 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2567 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2568 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002569 bool moveNeeded = false;
2570 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2571 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2572 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2573 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2574 mPointerGesture.lastGestureIdBits.value);
2575 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2576 mPointerGesture.currentGestureCoords,
2577 mPointerGesture.currentGestureIdToIndex,
2578 mPointerGesture.lastGestureProperties,
2579 mPointerGesture.lastGestureCoords,
2580 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2581 if (buttonState != mLastCookedState.buttonState) {
2582 moveNeeded = true;
2583 }
2584 }
2585
2586 // Send motion events for all pointers that went up or were canceled.
2587 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2588 if (!dispatchedGestureIdBits.isEmpty()) {
2589 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002590 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002591 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002592 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002593 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2594 mPointerGesture.lastGestureProperties,
2595 mPointerGesture.lastGestureCoords,
2596 mPointerGesture.lastGestureIdToIndex,
2597 dispatchedGestureIdBits, -1, 0, 0,
2598 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002599
2600 dispatchedGestureIdBits.clear();
2601 } else {
2602 BitSet32 upGestureIdBits;
2603 if (finishPreviousGesture) {
2604 upGestureIdBits = dispatchedGestureIdBits;
2605 } else {
2606 upGestureIdBits.value =
2607 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2608 }
2609 while (!upGestureIdBits.isEmpty()) {
2610 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2611
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002612 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2613 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2614 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2615 mPointerGesture.lastGestureProperties,
2616 mPointerGesture.lastGestureCoords,
2617 mPointerGesture.lastGestureIdToIndex,
2618 dispatchedGestureIdBits, id, 0, 0,
2619 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002620
2621 dispatchedGestureIdBits.clearBit(id);
2622 }
2623 }
2624 }
2625
2626 // Send motion events for all pointers that moved.
2627 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002628 out.push_back(
2629 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2630 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2631 mPointerGesture.currentGestureProperties,
2632 mPointerGesture.currentGestureCoords,
2633 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2634 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002635 }
2636
2637 // Send motion events for all pointers that went down.
2638 if (down) {
2639 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2640 ~dispatchedGestureIdBits.value);
2641 while (!downGestureIdBits.isEmpty()) {
2642 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2643 dispatchedGestureIdBits.markBit(id);
2644
2645 if (dispatchedGestureIdBits.count() == 1) {
2646 mPointerGesture.downTime = when;
2647 }
2648
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002649 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2650 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2651 buttonState, 0, mPointerGesture.currentGestureProperties,
2652 mPointerGesture.currentGestureCoords,
2653 mPointerGesture.currentGestureIdToIndex,
2654 dispatchedGestureIdBits, id, 0, 0,
2655 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002656 }
2657 }
2658
2659 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002660 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002661 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2662 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2663 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2664 mPointerGesture.currentGestureProperties,
2665 mPointerGesture.currentGestureCoords,
2666 mPointerGesture.currentGestureIdToIndex,
2667 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2668 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002669 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2670 // Synthesize a hover move event after all pointers go up to indicate that
2671 // the pointer is hovering again even if the user is not currently touching
2672 // the touch pad. This ensures that a view will receive a fresh hover enter
2673 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002674 float x, y;
2675 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002676
2677 PointerProperties pointerProperties;
2678 pointerProperties.clear();
2679 pointerProperties.id = 0;
2680 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2681
2682 PointerCoords pointerCoords;
2683 pointerCoords.clear();
2684 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2685 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2686
2687 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002688 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2689 mSource, displayId, policyFlags,
2690 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2691 buttonState, MotionClassification::NONE,
2692 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2693 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2694 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002695 }
2696
2697 // Update state.
2698 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2699 if (!down) {
2700 mPointerGesture.lastGestureIdBits.clear();
2701 } else {
2702 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2703 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2704 uint32_t id = idBits.clearFirstMarkedBit();
2705 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2706 mPointerGesture.lastGestureProperties[index].copyFrom(
2707 mPointerGesture.currentGestureProperties[index]);
2708 mPointerGesture.lastGestureCoords[index].copyFrom(
2709 mPointerGesture.currentGestureCoords[index]);
2710 mPointerGesture.lastGestureIdToIndex[id] = index;
2711 }
2712 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002713 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002714}
2715
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002716std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2717 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002718 const MotionClassification classification =
2719 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2720 ? MotionClassification::TWO_FINGER_SWIPE
2721 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002722 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002723 // Cancel previously dispatches pointers.
2724 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2725 int32_t metaState = getContext()->getGlobalMetaState();
2726 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002727 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002728 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2729 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002730 mPointerGesture.lastGestureProperties,
2731 mPointerGesture.lastGestureCoords,
2732 mPointerGesture.lastGestureIdToIndex,
2733 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2734 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002735 }
2736
2737 // Reset the current pointer gesture.
2738 mPointerGesture.reset();
2739 mPointerVelocityControl.reset();
2740
2741 // Remove any current spots.
2742 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002743 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002744 mPointerController->clearSpots();
2745 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002746 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002747}
2748
2749bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2750 bool* outFinishPreviousGesture, bool isTimeout) {
2751 *outCancelPreviousGesture = false;
2752 *outFinishPreviousGesture = false;
2753
2754 // Handle TAP timeout.
2755 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002756 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002757
Michael Wright227c5542020-07-02 18:30:52 +01002758 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002759 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2760 // The tap/drag timeout has not yet expired.
2761 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2762 mConfig.pointerGestureTapDragInterval);
2763 } else {
2764 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002765 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002766 *outFinishPreviousGesture = true;
2767
2768 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002769 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002770 mPointerGesture.currentGestureIdBits.clear();
2771
2772 mPointerVelocityControl.reset();
2773 return true;
2774 }
2775 }
2776
2777 // We did not handle this timeout.
2778 return false;
2779 }
2780
2781 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2782 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2783
2784 // Update the velocity tracker.
2785 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002786 std::vector<float> positionsX;
2787 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002788 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 uint32_t id = idBits.clearFirstMarkedBit();
2790 const RawPointerData::Pointer& pointer =
2791 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002792 positionsX.push_back(pointer.x * mPointerXMovementScale);
2793 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 }
2795 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002796 {{AMOTION_EVENT_AXIS_X, positionsX},
2797 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002798 }
2799
2800 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2801 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002802 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2803 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2804 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002805 mPointerGesture.resetTap();
2806 }
2807
2808 // Pick a new active touch id if needed.
2809 // Choose an arbitrary pointer that just went down, if there is one.
2810 // Otherwise choose an arbitrary remaining pointer.
2811 // This guarantees we always have an active touch id when there is at least one pointer.
2812 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002813 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002814 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002815 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002816 mPointerGesture.firstTouchTime = when;
2817 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002818 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2819 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2820 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2821 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002823 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824
2825 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002826 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002827 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002828 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2829 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2830 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002831 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002832 *outFinishPreviousGesture = true;
2833 }
2834
2835 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002836 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002837 mPointerGesture.currentGestureIdBits.clear();
2838
2839 mPointerVelocityControl.reset();
2840 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2841 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2842 // The pointer follows the active touch point.
2843 // Emit DOWN, MOVE, UP events at the pointer location.
2844 //
2845 // Only the active touch matters; other fingers are ignored. This policy helps
2846 // to handle the case where the user places a second finger on the touch pad
2847 // to apply the necessary force to depress an integrated button below the surface.
2848 // We don't want the second finger to be delivered to applications.
2849 //
2850 // For this to work well, we need to make sure to track the pointer that is really
2851 // active. If the user first puts one finger down to click then adds another
2852 // finger to drag then the active pointer should switch to the finger that is
2853 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002854 ALOGD_IF(DEBUG_GESTURES,
2855 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2856 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002858 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859 *outFinishPreviousGesture = true;
2860 mPointerGesture.activeGestureId = 0;
2861 }
2862
2863 // Switch pointers if needed.
2864 // Find the fastest pointer and follow it.
2865 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002866 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002868 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002869 ALOGD_IF(DEBUG_GESTURES,
2870 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2871 "bestSpeed=%0.3f",
2872 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 }
2874 }
2875
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002876 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002877 // When using spots, the click will occur at the position of the anchor
2878 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002879 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002880 } else {
2881 mPointerVelocityControl.reset();
2882 }
2883
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002884 float x, y;
2885 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886
Michael Wright227c5542020-07-02 18:30:52 +01002887 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002888 mPointerGesture.currentGestureIdBits.clear();
2889 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2890 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2891 mPointerGesture.currentGestureProperties[0].clear();
2892 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2893 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2894 mPointerGesture.currentGestureCoords[0].clear();
2895 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2896 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2897 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2898 } else if (currentFingerCount == 0) {
2899 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002900 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002901 *outFinishPreviousGesture = true;
2902 }
2903
2904 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2905 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2906 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002907 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2908 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002909 lastFingerCount == 1) {
2910 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002911 float x, y;
2912 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2914 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002915 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916
2917 mPointerGesture.tapUpTime = when;
2918 getContext()->requestTimeoutAtTime(when +
2919 mConfig.pointerGestureTapDragInterval);
2920
2921 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002922 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002923 mPointerGesture.currentGestureIdBits.clear();
2924 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2925 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2926 mPointerGesture.currentGestureProperties[0].clear();
2927 mPointerGesture.currentGestureProperties[0].id =
2928 mPointerGesture.activeGestureId;
2929 mPointerGesture.currentGestureProperties[0].toolType =
2930 AMOTION_EVENT_TOOL_TYPE_FINGER;
2931 mPointerGesture.currentGestureCoords[0].clear();
2932 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2933 mPointerGesture.tapX);
2934 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2935 mPointerGesture.tapY);
2936 mPointerGesture.currentGestureCoords[0]
2937 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2938
2939 tapped = true;
2940 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002941 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2942 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943 }
2944 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002945 if (DEBUG_GESTURES) {
2946 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2947 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2948 (when - mPointerGesture.tapDownTime) * 0.000001f);
2949 } else {
2950 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2951 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002953 }
2954 }
2955
2956 mPointerVelocityControl.reset();
2957
2958 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002959 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002960 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002961 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002962 mPointerGesture.currentGestureIdBits.clear();
2963 }
2964 } else if (currentFingerCount == 1) {
2965 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2966 // The pointer follows the active touch point.
2967 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2968 // When in TAP_DRAG, emit MOVE events at the pointer location.
2969 ALOG_ASSERT(activeTouchId >= 0);
2970
Michael Wright227c5542020-07-02 18:30:52 +01002971 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2972 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002974 float x, y;
2975 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002976 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2977 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002978 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002980 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2981 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002982 }
2983 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002984 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2985 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 }
Michael Wright227c5542020-07-02 18:30:52 +01002987 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2988 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 }
2990
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002992 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002993 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002994 } else {
2995 mPointerVelocityControl.reset();
2996 }
2997
2998 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002999 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003000 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003001 down = true;
3002 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003003 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003004 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003005 *outFinishPreviousGesture = true;
3006 }
3007 mPointerGesture.activeGestureId = 0;
3008 down = false;
3009 }
3010
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003011 float x, y;
3012 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003013
3014 mPointerGesture.currentGestureIdBits.clear();
3015 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3016 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3017 mPointerGesture.currentGestureProperties[0].clear();
3018 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3019 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3020 mPointerGesture.currentGestureCoords[0].clear();
3021 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3022 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3023 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3024 down ? 1.0f : 0.0f);
3025
3026 if (lastFingerCount == 0 && currentFingerCount != 0) {
3027 mPointerGesture.resetTap();
3028 mPointerGesture.tapDownTime = when;
3029 mPointerGesture.tapX = x;
3030 mPointerGesture.tapY = y;
3031 }
3032 } else {
3033 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003034 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003035 }
3036
3037 mPointerController->setButtonState(mCurrentRawState.buttonState);
3038
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003039 if (DEBUG_GESTURES) {
3040 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3041 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3042 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3043 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3044 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3045 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3046 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3047 uint32_t id = idBits.clearFirstMarkedBit();
3048 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3049 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3050 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3051 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3052 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3053 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3054 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3055 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3056 }
3057 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3058 uint32_t id = idBits.clearFirstMarkedBit();
3059 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3060 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3061 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3062 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3063 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3064 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3065 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3066 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3067 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003068 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003069 return true;
3070}
3071
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003072bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3073 if (mPointerGesture.activeTouchId < 0) {
3074 mPointerGesture.resetQuietTime();
3075 return false;
3076 }
3077
3078 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3079 return true;
3080 }
3081
3082 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3083 bool isQuietTime = false;
3084 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3085 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3086 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3087 currentFingerCount < 2) {
3088 // Enter quiet time when exiting swipe or freeform state.
3089 // This is to prevent accidentally entering the hover state and flinging the
3090 // pointer when finishing a swipe and there is still one pointer left onscreen.
3091 isQuietTime = true;
3092 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3093 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3094 // Enter quiet time when releasing the button and there are still two or more
3095 // fingers down. This may indicate that one finger was used to press the button
3096 // but it has not gone up yet.
3097 isQuietTime = true;
3098 }
3099 if (isQuietTime) {
3100 mPointerGesture.quietTime = when;
3101 }
3102 return isQuietTime;
3103}
3104
3105std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3106 int32_t bestId = -1;
3107 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3108 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3109 uint32_t id = idBits.clearFirstMarkedBit();
3110 std::optional<float> vx =
3111 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3112 std::optional<float> vy =
3113 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3114 if (vx && vy) {
3115 float speed = hypotf(*vx, *vy);
3116 if (speed > bestSpeed) {
3117 bestId = id;
3118 bestSpeed = speed;
3119 }
3120 }
3121 }
3122 return std::make_pair(bestId, bestSpeed);
3123}
3124
3125void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3126 bool* finishPreviousGesture) {
3127 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3128 // to move before deciding what to do.
3129 //
3130 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3131 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3132 // just a press or long-press at the pointer location.
3133 //
3134 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3135 // pointer location.
3136 //
3137 // When the two fingers move enough or when additional fingers are added, we make a decision to
3138 // transition into SWIPE or FREEFORM mode accordingly.
3139 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3140 ALOG_ASSERT(activeTouchId >= 0);
3141
3142 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3143 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3144 bool settled =
3145 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3146 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3147 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3148 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3149 *finishPreviousGesture = true;
3150 } else if (!settled && currentFingerCount > lastFingerCount) {
3151 // Additional pointers have gone down but not yet settled.
3152 // Reset the gesture.
3153 ALOGD_IF(DEBUG_GESTURES,
3154 "Gestures: Resetting gesture since additional pointers went down for "
3155 "MULTITOUCH, settle time remaining %0.3fms",
3156 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3157 when) * 0.000001f);
3158 *cancelPreviousGesture = true;
3159 } else {
3160 // Continue previous gesture.
3161 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3162 }
3163
3164 if (*finishPreviousGesture || *cancelPreviousGesture) {
3165 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3166 mPointerGesture.activeGestureId = 0;
3167 mPointerGesture.referenceIdBits.clear();
3168 mPointerVelocityControl.reset();
3169
3170 // Use the centroid and pointer location as the reference points for the gesture.
3171 ALOGD_IF(DEBUG_GESTURES,
3172 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3173 "%0.3fms",
3174 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3175 when) * 0.000001f);
3176 mCurrentRawState.rawPointerData
3177 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3178 &mPointerGesture.referenceTouchY);
3179 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3180 &mPointerGesture.referenceGestureY);
3181 }
3182
3183 // Clear the reference deltas for fingers not yet included in the reference calculation.
3184 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3185 ~mPointerGesture.referenceIdBits.value);
3186 !idBits.isEmpty();) {
3187 uint32_t id = idBits.clearFirstMarkedBit();
3188 mPointerGesture.referenceDeltas[id].dx = 0;
3189 mPointerGesture.referenceDeltas[id].dy = 0;
3190 }
3191 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3192
3193 // Add delta for all fingers and calculate a common movement delta.
3194 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3195 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3196 mCurrentCookedState.fingerIdBits.value);
3197 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3198 bool first = (idBits == commonIdBits);
3199 uint32_t id = idBits.clearFirstMarkedBit();
3200 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3201 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3202 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3203 delta.dx += cpd.x - lpd.x;
3204 delta.dy += cpd.y - lpd.y;
3205
3206 if (first) {
3207 commonDeltaRawX = delta.dx;
3208 commonDeltaRawY = delta.dy;
3209 } else {
3210 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3211 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3212 }
3213 }
3214
3215 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3216 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3217 float dist[MAX_POINTER_ID + 1];
3218 int32_t distOverThreshold = 0;
3219 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3220 uint32_t id = idBits.clearFirstMarkedBit();
3221 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3222 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3223 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3224 distOverThreshold += 1;
3225 }
3226 }
3227
3228 // Only transition when at least two pointers have moved further than
3229 // the minimum distance threshold.
3230 if (distOverThreshold >= 2) {
3231 if (currentFingerCount > 2) {
3232 // There are more than two pointers, switch to FREEFORM.
3233 ALOGD_IF(DEBUG_GESTURES,
3234 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3235 currentFingerCount);
3236 *cancelPreviousGesture = true;
3237 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3238 } else {
3239 // There are exactly two pointers.
3240 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3241 uint32_t id1 = idBits.clearFirstMarkedBit();
3242 uint32_t id2 = idBits.firstMarkedBit();
3243 const RawPointerData::Pointer& p1 =
3244 mCurrentRawState.rawPointerData.pointerForId(id1);
3245 const RawPointerData::Pointer& p2 =
3246 mCurrentRawState.rawPointerData.pointerForId(id2);
3247 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3248 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3249 // There are two pointers but they are too far apart for a SWIPE,
3250 // switch to FREEFORM.
3251 ALOGD_IF(DEBUG_GESTURES,
3252 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3253 mutualDistance, mPointerGestureMaxSwipeWidth);
3254 *cancelPreviousGesture = true;
3255 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3256 } else {
3257 // There are two pointers. Wait for both pointers to start moving
3258 // before deciding whether this is a SWIPE or FREEFORM gesture.
3259 float dist1 = dist[id1];
3260 float dist2 = dist[id2];
3261 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3262 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3263 // Calculate the dot product of the displacement vectors.
3264 // When the vectors are oriented in approximately the same direction,
3265 // the angle betweeen them is near zero and the cosine of the angle
3266 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3267 // mag(v2).
3268 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3269 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3270 float dx1 = delta1.dx * mPointerXZoomScale;
3271 float dy1 = delta1.dy * mPointerYZoomScale;
3272 float dx2 = delta2.dx * mPointerXZoomScale;
3273 float dy2 = delta2.dy * mPointerYZoomScale;
3274 float dot = dx1 * dx2 + dy1 * dy2;
3275 float cosine = dot / (dist1 * dist2); // denominator always > 0
3276 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3277 // Pointers are moving in the same direction. Switch to SWIPE.
3278 ALOGD_IF(DEBUG_GESTURES,
3279 "Gestures: PRESS transitioned to SWIPE, "
3280 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3281 "cosine %0.3f >= %0.3f",
3282 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3283 mConfig.pointerGestureMultitouchMinDistance, cosine,
3284 mConfig.pointerGestureSwipeTransitionAngleCosine);
3285 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3286 } else {
3287 // Pointers are moving in different directions. Switch to FREEFORM.
3288 ALOGD_IF(DEBUG_GESTURES,
3289 "Gestures: PRESS transitioned to FREEFORM, "
3290 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3291 "cosine %0.3f < %0.3f",
3292 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3293 mConfig.pointerGestureMultitouchMinDistance, cosine,
3294 mConfig.pointerGestureSwipeTransitionAngleCosine);
3295 *cancelPreviousGesture = true;
3296 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3297 }
3298 }
3299 }
3300 }
3301 }
3302 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3303 // Switch from SWIPE to FREEFORM if additional pointers go down.
3304 // Cancel previous gesture.
3305 if (currentFingerCount > 2) {
3306 ALOGD_IF(DEBUG_GESTURES,
3307 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3308 currentFingerCount);
3309 *cancelPreviousGesture = true;
3310 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3311 }
3312 }
3313
3314 // Move the reference points based on the overall group motion of the fingers
3315 // except in PRESS mode while waiting for a transition to occur.
3316 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3317 (commonDeltaRawX || commonDeltaRawY)) {
3318 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3319 uint32_t id = idBits.clearFirstMarkedBit();
3320 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3321 delta.dx = 0;
3322 delta.dy = 0;
3323 }
3324
3325 mPointerGesture.referenceTouchX += commonDeltaRawX;
3326 mPointerGesture.referenceTouchY += commonDeltaRawY;
3327
3328 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3329 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3330
3331 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3332 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3333
3334 mPointerGesture.referenceGestureX += commonDeltaX;
3335 mPointerGesture.referenceGestureY += commonDeltaY;
3336 }
3337
3338 // Report gestures.
3339 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3340 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3341 // PRESS or SWIPE mode.
3342 ALOGD_IF(DEBUG_GESTURES,
3343 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3344 "currentTouchPointerCount=%d",
3345 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3346 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3347
3348 mPointerGesture.currentGestureIdBits.clear();
3349 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3350 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3351 mPointerGesture.currentGestureProperties[0].clear();
3352 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3353 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3354 mPointerGesture.currentGestureCoords[0].clear();
3355 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3356 mPointerGesture.referenceGestureX);
3357 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3358 mPointerGesture.referenceGestureY);
3359 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3360 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3361 float xOffset = static_cast<float>(commonDeltaRawX) /
3362 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3363 float yOffset = static_cast<float>(commonDeltaRawY) /
3364 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3365 mPointerGesture.currentGestureCoords[0]
3366 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3367 mPointerGesture.currentGestureCoords[0]
3368 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3369 }
3370 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3371 // FREEFORM mode.
3372 ALOGD_IF(DEBUG_GESTURES,
3373 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3374 "currentTouchPointerCount=%d",
3375 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3376 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3377
3378 mPointerGesture.currentGestureIdBits.clear();
3379
3380 BitSet32 mappedTouchIdBits;
3381 BitSet32 usedGestureIdBits;
3382 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3383 // Initially, assign the active gesture id to the active touch point
3384 // if there is one. No other touch id bits are mapped yet.
3385 if (!*cancelPreviousGesture) {
3386 mappedTouchIdBits.markBit(activeTouchId);
3387 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3388 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3389 mPointerGesture.activeGestureId;
3390 } else {
3391 mPointerGesture.activeGestureId = -1;
3392 }
3393 } else {
3394 // Otherwise, assume we mapped all touches from the previous frame.
3395 // Reuse all mappings that are still applicable.
3396 mappedTouchIdBits.value =
3397 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3398 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3399
3400 // Check whether we need to choose a new active gesture id because the
3401 // current went went up.
3402 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3403 ~mCurrentCookedState.fingerIdBits.value);
3404 !upTouchIdBits.isEmpty();) {
3405 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3406 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3407 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3408 mPointerGesture.activeGestureId = -1;
3409 break;
3410 }
3411 }
3412 }
3413
3414 ALOGD_IF(DEBUG_GESTURES,
3415 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3416 "activeGestureId=%d",
3417 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3418
3419 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3420 for (uint32_t i = 0; i < currentFingerCount; i++) {
3421 uint32_t touchId = idBits.clearFirstMarkedBit();
3422 uint32_t gestureId;
3423 if (!mappedTouchIdBits.hasBit(touchId)) {
3424 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3425 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3426 ALOGD_IF(DEBUG_GESTURES,
3427 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3428 gestureId);
3429 } else {
3430 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3431 ALOGD_IF(DEBUG_GESTURES,
3432 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3433 touchId, gestureId);
3434 }
3435 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3436 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3437
3438 const RawPointerData::Pointer& pointer =
3439 mCurrentRawState.rawPointerData.pointerForId(touchId);
3440 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3441 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3442 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3443
3444 mPointerGesture.currentGestureProperties[i].clear();
3445 mPointerGesture.currentGestureProperties[i].id = gestureId;
3446 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3447 mPointerGesture.currentGestureCoords[i].clear();
3448 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3449 mPointerGesture.referenceGestureX +
3450 deltaX);
3451 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3452 mPointerGesture.referenceGestureY +
3453 deltaY);
3454 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3455 }
3456
3457 if (mPointerGesture.activeGestureId < 0) {
3458 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3459 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3460 mPointerGesture.activeGestureId);
3461 }
3462 }
3463}
3464
Harry Cutts714d1ad2022-08-24 16:36:43 +00003465void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3466 const RawPointerData::Pointer& currentPointer =
3467 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3468 const RawPointerData::Pointer& lastPointer =
3469 mLastRawState.rawPointerData.pointerForId(pointerId);
3470 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3471 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3472
3473 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3474 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3475
3476 mPointerController->move(deltaX, deltaY);
3477}
3478
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003479std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3480 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003481 mPointerSimple.currentCoords.clear();
3482 mPointerSimple.currentProperties.clear();
3483
3484 bool down, hovering;
3485 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3486 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3487 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003488 mPointerController
3489 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3490 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003491
3492 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3493 down = !hovering;
3494
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003495 float x, y;
3496 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003497 mPointerSimple.currentCoords.copyFrom(
3498 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3499 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3500 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3501 mPointerSimple.currentProperties.id = 0;
3502 mPointerSimple.currentProperties.toolType =
3503 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3504 } else {
3505 down = false;
3506 hovering = false;
3507 }
3508
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003509 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003510}
3511
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003512std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3513 uint32_t policyFlags) {
3514 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515}
3516
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003517std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3518 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003519 mPointerSimple.currentCoords.clear();
3520 mPointerSimple.currentProperties.clear();
3521
3522 bool down, hovering;
3523 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3524 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003525 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003526 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527 } else {
3528 mPointerVelocityControl.reset();
3529 }
3530
3531 down = isPointerDown(mCurrentRawState.buttonState);
3532 hovering = !down;
3533
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003534 float x, y;
3535 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003536 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003537 mPointerSimple.currentCoords.copyFrom(
3538 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3539 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3540 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3541 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3542 hovering ? 0.0f : 1.0f);
3543 mPointerSimple.currentProperties.id = 0;
3544 mPointerSimple.currentProperties.toolType =
3545 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3546 } else {
3547 mPointerVelocityControl.reset();
3548
3549 down = false;
3550 hovering = false;
3551 }
3552
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003553 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003554}
3555
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003556std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3557 uint32_t policyFlags) {
3558 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003559
3560 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003561
3562 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563}
3564
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003565std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3566 uint32_t policyFlags, bool down,
3567 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003568 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3569 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003570 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572
3573 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003574 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003575 mPointerController->clearSpots();
3576 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003577 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003578 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003579 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003580 }
Garfield Tan9514d782020-11-10 16:37:23 -08003581 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003582
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003583 float xCursorPosition, yCursorPosition;
3584 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003585
3586 if (mPointerSimple.down && !down) {
3587 mPointerSimple.down = false;
3588
3589 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003590 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3591 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3592 0, metaState, mLastRawState.buttonState,
3593 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3594 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3595 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3596 yCursorPosition, mPointerSimple.downTime,
3597 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598 }
3599
3600 if (mPointerSimple.hovering && !hovering) {
3601 mPointerSimple.hovering = false;
3602
3603 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003604 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3605 mSource, displayId, policyFlags,
3606 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3607 mLastRawState.buttonState, MotionClassification::NONE,
3608 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3609 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3610 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3611 yCursorPosition, mPointerSimple.downTime,
3612 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003613 }
3614
3615 if (down) {
3616 if (!mPointerSimple.down) {
3617 mPointerSimple.down = true;
3618 mPointerSimple.downTime = when;
3619
3620 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003621 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3622 mSource, displayId, policyFlags,
3623 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3624 mCurrentRawState.buttonState, MotionClassification::NONE,
3625 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3626 &mPointerSimple.currentProperties,
3627 &mPointerSimple.currentCoords, mOrientedXPrecision,
3628 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3629 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003630 }
3631
3632 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003633 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3634 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3635 0, 0, metaState, mCurrentRawState.buttonState,
3636 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3637 &mPointerSimple.currentProperties,
3638 &mPointerSimple.currentCoords, mOrientedXPrecision,
3639 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3640 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003641 }
3642
3643 if (hovering) {
3644 if (!mPointerSimple.hovering) {
3645 mPointerSimple.hovering = true;
3646
3647 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003648 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3649 mSource, displayId, policyFlags,
3650 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3651 mCurrentRawState.buttonState, MotionClassification::NONE,
3652 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3653 &mPointerSimple.currentProperties,
3654 &mPointerSimple.currentCoords, mOrientedXPrecision,
3655 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3656 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003657 }
3658
3659 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003660 out.push_back(
3661 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3662 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3663 metaState, mCurrentRawState.buttonState,
3664 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3665 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3666 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3667 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003668 }
3669
3670 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3671 float vscroll = mCurrentRawState.rawVScroll;
3672 float hscroll = mCurrentRawState.rawHScroll;
3673 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3674 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3675
3676 // Send scroll.
3677 PointerCoords pointerCoords;
3678 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3679 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3680 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3681
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003682 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3683 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3684 0, 0, metaState, mCurrentRawState.buttonState,
3685 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3686 &mPointerSimple.currentProperties, &pointerCoords,
3687 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3688 yCursorPosition, mPointerSimple.downTime,
3689 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003690 }
3691
3692 // Save state.
3693 if (down || hovering) {
3694 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3695 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003696 mPointerSimple.displayId = displayId;
3697 mPointerSimple.source = mSource;
3698 mPointerSimple.lastCursorX = xCursorPosition;
3699 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003700 } else {
3701 mPointerSimple.reset();
3702 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003703 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003704}
3705
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003706std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3707 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003708 std::list<NotifyArgs> out;
3709 if (mPointerSimple.down || mPointerSimple.hovering) {
3710 int32_t metaState = getContext()->getGlobalMetaState();
3711 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3712 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3713 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3714 metaState, mLastRawState.buttonState,
3715 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3716 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3717 mOrientedXPrecision, mOrientedYPrecision,
3718 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3719 mPointerSimple.downTime,
3720 /* videoFrames */ {}));
3721 if (mPointerController != nullptr) {
3722 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3723 }
3724 }
3725 mPointerSimple.reset();
3726 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003727}
3728
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003729NotifyMotionArgs TouchInputMapper::dispatchMotion(
3730 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3731 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003732 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3733 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003734 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003735 PointerCoords pointerCoords[MAX_POINTERS];
3736 PointerProperties pointerProperties[MAX_POINTERS];
3737 uint32_t pointerCount = 0;
3738 while (!idBits.isEmpty()) {
3739 uint32_t id = idBits.clearFirstMarkedBit();
3740 uint32_t index = idToIndex[id];
3741 pointerProperties[pointerCount].copyFrom(properties[index]);
3742 pointerCoords[pointerCount].copyFrom(coords[index]);
3743
3744 if (changedId >= 0 && id == uint32_t(changedId)) {
3745 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3746 }
3747
3748 pointerCount += 1;
3749 }
3750
3751 ALOG_ASSERT(pointerCount != 0);
3752
3753 if (changedId >= 0 && pointerCount == 1) {
3754 // Replace initial down and final up action.
3755 // We can compare the action without masking off the changed pointer index
3756 // because we know the index is 0.
3757 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3758 action = AMOTION_EVENT_ACTION_DOWN;
3759 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003760 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3761 action = AMOTION_EVENT_ACTION_CANCEL;
3762 } else {
3763 action = AMOTION_EVENT_ACTION_UP;
3764 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003765 } else {
3766 // Can't happen.
3767 ALOG_ASSERT(false);
3768 }
3769 }
3770 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3771 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003772 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003773 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003774 }
3775 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3776 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003777 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003778 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003779 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003780 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3781 policyFlags, action, actionButton, flags, metaState, buttonState,
3782 classification, edgeFlags, pointerCount, pointerProperties,
3783 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3784 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003785}
3786
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003787std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3788 std::list<NotifyArgs> out;
3789 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3790 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3791 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003792}
3793
Prabir Pradhan1728b212021-10-19 16:00:03 -07003794// Transform input device coordinates to display panel coordinates.
3795void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003796 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3797 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3798
arthurhunga36b28e2020-12-29 20:28:15 +08003799 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3800 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3801
Prabir Pradhan1728b212021-10-19 16:00:03 -07003802 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003803 // 0 - no swap and reverse.
3804 // 90 - swap x/y and reverse y.
3805 // 180 - reverse x, y.
3806 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003807 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003808 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003809 x = xScaled;
3810 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003811 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003812 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003813 y = xScaledMax;
3814 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003815 break;
3816 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003817 x = xScaledMax;
3818 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003819 break;
3820 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003821 y = xScaled;
3822 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003823 break;
3824 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003825 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003826 }
3827}
3828
Prabir Pradhan1728b212021-10-19 16:00:03 -07003829bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003830 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3831 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3832
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003833 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003834 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00003835 isPointInRect(mPhysicalFrameInDisplay, xScaled, yScaled);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003836}
3837
3838const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3839 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003840 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3841 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3842 "left=%d, top=%d, right=%d, bottom=%d",
3843 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3844 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003845
3846 if (virtualKey.isHit(x, y)) {
3847 return &virtualKey;
3848 }
3849 }
3850
3851 return nullptr;
3852}
3853
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003854void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3855 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3856 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003857
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003858 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003859
3860 if (currentPointerCount == 0) {
3861 // No pointers to assign.
3862 return;
3863 }
3864
3865 if (lastPointerCount == 0) {
3866 // All pointers are new.
3867 for (uint32_t i = 0; i < currentPointerCount; i++) {
3868 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003869 current.rawPointerData.pointers[i].id = id;
3870 current.rawPointerData.idToIndex[id] = i;
3871 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003872 }
3873 return;
3874 }
3875
3876 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003877 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003878 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003879 uint32_t id = last.rawPointerData.pointers[0].id;
3880 current.rawPointerData.pointers[0].id = id;
3881 current.rawPointerData.idToIndex[id] = 0;
3882 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003883 return;
3884 }
3885
3886 // General case.
3887 // We build a heap of squared euclidean distances between current and last pointers
3888 // associated with the current and last pointer indices. Then, we find the best
3889 // match (by distance) for each current pointer.
3890 // The pointers must have the same tool type but it is possible for them to
3891 // transition from hovering to touching or vice-versa while retaining the same id.
3892 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3893
3894 uint32_t heapSize = 0;
3895 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3896 currentPointerIndex++) {
3897 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3898 lastPointerIndex++) {
3899 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003900 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003901 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003902 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003903 if (currentPointer.toolType == lastPointer.toolType) {
3904 int64_t deltaX = currentPointer.x - lastPointer.x;
3905 int64_t deltaY = currentPointer.y - lastPointer.y;
3906
3907 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3908
3909 // Insert new element into the heap (sift up).
3910 heap[heapSize].currentPointerIndex = currentPointerIndex;
3911 heap[heapSize].lastPointerIndex = lastPointerIndex;
3912 heap[heapSize].distance = distance;
3913 heapSize += 1;
3914 }
3915 }
3916 }
3917
3918 // Heapify
3919 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3920 startIndex -= 1;
3921 for (uint32_t parentIndex = startIndex;;) {
3922 uint32_t childIndex = parentIndex * 2 + 1;
3923 if (childIndex >= heapSize) {
3924 break;
3925 }
3926
3927 if (childIndex + 1 < heapSize &&
3928 heap[childIndex + 1].distance < heap[childIndex].distance) {
3929 childIndex += 1;
3930 }
3931
3932 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3933 break;
3934 }
3935
3936 swap(heap[parentIndex], heap[childIndex]);
3937 parentIndex = childIndex;
3938 }
3939 }
3940
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003941 if (DEBUG_POINTER_ASSIGNMENT) {
3942 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3943 for (size_t i = 0; i < heapSize; i++) {
3944 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3945 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3946 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003947 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003948
3949 // Pull matches out by increasing order of distance.
3950 // To avoid reassigning pointers that have already been matched, the loop keeps track
3951 // of which last and current pointers have been matched using the matchedXXXBits variables.
3952 // It also tracks the used pointer id bits.
3953 BitSet32 matchedLastBits(0);
3954 BitSet32 matchedCurrentBits(0);
3955 BitSet32 usedIdBits(0);
3956 bool first = true;
3957 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3958 while (heapSize > 0) {
3959 if (first) {
3960 // The first time through the loop, we just consume the root element of
3961 // the heap (the one with smallest distance).
3962 first = false;
3963 } else {
3964 // Previous iterations consumed the root element of the heap.
3965 // Pop root element off of the heap (sift down).
3966 heap[0] = heap[heapSize];
3967 for (uint32_t parentIndex = 0;;) {
3968 uint32_t childIndex = parentIndex * 2 + 1;
3969 if (childIndex >= heapSize) {
3970 break;
3971 }
3972
3973 if (childIndex + 1 < heapSize &&
3974 heap[childIndex + 1].distance < heap[childIndex].distance) {
3975 childIndex += 1;
3976 }
3977
3978 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3979 break;
3980 }
3981
3982 swap(heap[parentIndex], heap[childIndex]);
3983 parentIndex = childIndex;
3984 }
3985
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003986 if (DEBUG_POINTER_ASSIGNMENT) {
3987 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3988 for (size_t j = 0; j < heapSize; j++) {
3989 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3990 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3991 heap[j].distance);
3992 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003993 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003994 }
3995
3996 heapSize -= 1;
3997
3998 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3999 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4000
4001 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4002 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4003
4004 matchedCurrentBits.markBit(currentPointerIndex);
4005 matchedLastBits.markBit(lastPointerIndex);
4006
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004007 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4008 current.rawPointerData.pointers[currentPointerIndex].id = id;
4009 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4010 current.rawPointerData.markIdBit(id,
4011 current.rawPointerData.isHovering(
4012 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004013 usedIdBits.markBit(id);
4014
Harry Cutts45483602022-08-24 14:36:48 +00004015 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4016 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4017 ", distance=%" PRIu64,
4018 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004019 break;
4020 }
4021 }
4022
4023 // Assign fresh ids to pointers that were not matched in the process.
4024 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4025 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4026 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4027
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004028 current.rawPointerData.pointers[currentPointerIndex].id = id;
4029 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4030 current.rawPointerData.markIdBit(id,
4031 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004032
Harry Cutts45483602022-08-24 14:36:48 +00004033 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4034 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4035 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004036 }
4037}
4038
4039int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4040 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4041 return AKEY_STATE_VIRTUAL;
4042 }
4043
4044 for (const VirtualKey& virtualKey : mVirtualKeys) {
4045 if (virtualKey.keyCode == keyCode) {
4046 return AKEY_STATE_UP;
4047 }
4048 }
4049
4050 return AKEY_STATE_UNKNOWN;
4051}
4052
4053int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4054 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4055 return AKEY_STATE_VIRTUAL;
4056 }
4057
4058 for (const VirtualKey& virtualKey : mVirtualKeys) {
4059 if (virtualKey.scanCode == scanCode) {
4060 return AKEY_STATE_UP;
4061 }
4062 }
4063
4064 return AKEY_STATE_UNKNOWN;
4065}
4066
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004067bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4068 const std::vector<int32_t>& keyCodes,
4069 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004070 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004071 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004072 if (virtualKey.keyCode == keyCodes[i]) {
4073 outFlags[i] = 1;
4074 }
4075 }
4076 }
4077
4078 return true;
4079}
4080
4081std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4082 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004083 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004084 return std::make_optional(mPointerController->getDisplayId());
4085 } else {
4086 return std::make_optional(mViewport.displayId);
4087 }
4088 }
4089 return std::nullopt;
4090}
4091
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004092} // namespace android