blob: 80e1a8900a059d075a413d5252fa2a27176b11b3 [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"
Michael Wrighta9cf4192022-12-01 23:46:39 +000030#include "ui/Rotation.h"
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070031
32namespace android {
33
34// --- Constants ---
35
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070036// Artificial latency on synthetic events created from stylus data without corresponding touch
37// data.
38static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
39
HQ Liue6983c72022-04-19 22:14:56 +000040// Minimum width between two pointers to determine a gesture as freeform gesture in mm
41static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070042// --- Static Definitions ---
43
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000044static const DisplayViewport kUninitializedViewport;
45
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000046static std::string toString(const Rect& rect) {
47 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
48}
49
50static std::string toString(const ui::Size& size) {
51 return base::StringPrintf("%dx%d", size.width, size.height);
52}
53
Prabir Pradhan675f25a2022-11-10 22:04:07 +000054static bool isPointInRect(const Rect& rect, vec2 p) {
55 return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000056}
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 Pradhan675f25a2022-11-10 22:04:07 +000083static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000084 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000085 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000086 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
87 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +000088 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +000089}
90
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070091// --- RawPointerData ---
92
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070093void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
94 float x = 0, y = 0;
95 uint32_t count = touchingIdBits.count();
96 if (count) {
97 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
98 uint32_t id = idBits.clearFirstMarkedBit();
99 const Pointer& pointer = pointerForId(id);
100 x += pointer.x;
101 y += pointer.y;
102 }
103 x /= count;
104 y /= count;
105 }
106 *outX = x;
107 *outY = y;
108}
109
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700110// --- TouchInputMapper ---
111
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800112TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
113 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000114 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700115 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100116 mDeviceMode(DeviceMode::DISABLED),
Michael Wrighta9cf4192022-12-01 23:46:39 +0000117 mInputDeviceOrientation(ui::ROTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700118
119TouchInputMapper::~TouchInputMapper() {}
120
Philip Junker4af3b3d2021-12-14 10:36:55 +0100121uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700122 return mSource;
123}
124
125void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
126 InputMapper::populateDeviceInfo(info);
127
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000128 if (mDeviceMode == DeviceMode::DISABLED) {
129 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700130 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000131
132 info->addMotionRange(mOrientedRanges.x);
133 info->addMotionRange(mOrientedRanges.y);
134 info->addMotionRange(mOrientedRanges.pressure);
135
136 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
137 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
138 //
139 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
140 // motion, i.e. the hardware dimensions, as the finger could move completely across the
141 // touchpad in one sample cycle.
142 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
143 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
144 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
145 x.resolution);
146 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
147 y.resolution);
148 }
149
150 if (mOrientedRanges.size) {
151 info->addMotionRange(*mOrientedRanges.size);
152 }
153
154 if (mOrientedRanges.touchMajor) {
155 info->addMotionRange(*mOrientedRanges.touchMajor);
156 info->addMotionRange(*mOrientedRanges.touchMinor);
157 }
158
159 if (mOrientedRanges.toolMajor) {
160 info->addMotionRange(*mOrientedRanges.toolMajor);
161 info->addMotionRange(*mOrientedRanges.toolMinor);
162 }
163
164 if (mOrientedRanges.orientation) {
165 info->addMotionRange(*mOrientedRanges.orientation);
166 }
167
168 if (mOrientedRanges.distance) {
169 info->addMotionRange(*mOrientedRanges.distance);
170 }
171
172 if (mOrientedRanges.tilt) {
173 info->addMotionRange(*mOrientedRanges.tilt);
174 }
175
176 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
177 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
178 }
179 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
180 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
181 }
182 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
183 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
184 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
185 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
186 x.resolution);
187 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
188 y.resolution);
189 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
190 x.resolution);
191 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
192 y.resolution);
193 }
194 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000195 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700196}
197
198void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700199 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800200 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700201 dumpParameters(dump);
202 dumpVirtualKeys(dump);
203 dumpRawPointerAxes(dump);
204 dumpCalibration(dump);
205 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700206 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207
208 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000209 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000210 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
211 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
212 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700213 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
214 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
215 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
216 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
217 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
218 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
219 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
220 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
221 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
222 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
223
224 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
225 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
226 mLastRawState.rawPointerData.pointerCount);
227 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
228 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
229 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
230 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
231 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
232 "toolType=%d, isHovering=%s\n",
233 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
234 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
235 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
236 pointer.distance, pointer.toolType, toString(pointer.isHovering));
237 }
238
239 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
240 mLastCookedState.buttonState);
241 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
242 mLastCookedState.cookedPointerData.pointerCount);
243 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
244 const PointerProperties& pointerProperties =
245 mLastCookedState.cookedPointerData.pointerProperties[i];
246 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000247 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
248 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
249 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700250 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
251 "toolType=%d, isHovering=%s\n",
252 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000253 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
254 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700255 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
263 pointerProperties.toolType,
264 toString(mLastCookedState.cookedPointerData.isHovering(i)));
265 }
266
267 dump += INDENT3 "Stylus Fusion:\n";
268 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
269 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000270 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
271 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700272 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
273 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000274 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
275 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700276 dump += INDENT3 "External Stylus State:\n";
277 dumpStylusState(dump, mExternalStylusState);
278
Michael Wright227c5542020-07-02 18:30:52 +0100279 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700280 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
281 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
282 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
283 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
284 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
285 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
286 }
287}
288
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700289std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
290 const InputReaderConfiguration* config,
291 uint32_t changes) {
292 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700293
294 mConfig = *config;
295
296 if (!changes) { // first time only
297 // Configure basic parameters.
298 configureParameters();
299
300 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800301 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000302 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700303
304 // Configure absolute axis information.
305 configureRawPointerAxes();
306
307 // Prepare input device calibration.
308 parseCalibration();
309 resolveCalibration();
310 }
311
312 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
313 // Update location calibration to reflect current settings
314 updateAffineTransformation();
315 }
316
317 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
318 // Update pointer speed.
319 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
320 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
321 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
322 }
323
324 bool resetNeeded = false;
325 if (!changes ||
326 (changes &
327 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800328 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700329 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
330 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
331 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700332 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700334 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700335 }
336
337 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700338 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000339
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700340 // Send reset, unless this is the first time the device has been configured,
341 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000342 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700343 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700344 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345}
346
347void TouchInputMapper::resolveExternalStylusPresence() {
348 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800349 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350 mExternalStylusConnected = !devices.empty();
351
352 if (!mExternalStylusConnected) {
353 resetExternalStylus();
354 }
355}
356
357void TouchInputMapper::configureParameters() {
358 // Use the pointer presentation mode for devices that do not support distinct
359 // multitouch. The spot-based presentation relies on being able to accurately
360 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100362 ? Parameters::GestureMode::SINGLE_TOUCH
363 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700365 std::string gestureModeString;
366 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800367 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700368 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100369 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700370 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100371 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700372 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700373 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374 }
375 }
376
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000377 configureDeviceType();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700378
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800379 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700380
Michael Wright227c5542020-07-02 18:30:52 +0100381 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700382 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800383 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384
Michael Wrighta9cf4192022-12-01 23:46:39 +0000385 mParameters.orientation = ui::ROTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700386 std::string orientationString;
387 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700388 orientationString)) {
389 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
390 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
391 } else if (orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000392 mParameters.orientation = ui::ROTATION_90;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700393 } else if (orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000394 mParameters.orientation = ui::ROTATION_180;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700395 } else if (orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000396 mParameters.orientation = ui::ROTATION_270;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700397 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700398 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700399 }
400 }
401
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 mParameters.hasAssociatedDisplay = false;
403 mParameters.associatedDisplayIsExternal = false;
404 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100405 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000406 mParameters.deviceType == Parameters::DeviceType::POINTER ||
407 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
408 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700409 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100410 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800411 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700412 std::string uniqueDisplayId;
413 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800414 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700415 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
416 }
417 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700419 mParameters.hasAssociatedDisplay = true;
420 }
421
422 // Initial downs on external touch devices should wake the device.
423 // Normally we don't do this for internal touch screens to prevent them from waking
424 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800425 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700426 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000427
428 mParameters.supportsUsi = false;
429 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
430 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700431
432 mParameters.enableForInactiveViewport = false;
433 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
434 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700435}
436
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000437void TouchInputMapper::configureDeviceType() {
438 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
439 // The device is a touch screen.
440 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
441 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
442 // The device is a pointing device like a track pad.
443 mParameters.deviceType = Parameters::DeviceType::POINTER;
444 } else {
445 // The device is a touch pad of unknown purpose.
446 mParameters.deviceType = Parameters::DeviceType::POINTER;
447 }
448
449 // Type association takes precedence over the device type found in the idc file.
450 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
451 if (deviceTypeString.empty()) {
452 getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType", deviceTypeString);
453 }
454 if (deviceTypeString == "touchScreen") {
455 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
456 } else if (deviceTypeString == "touchNavigation") {
457 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
458 } else if (deviceTypeString == "pointer") {
459 mParameters.deviceType = Parameters::DeviceType::POINTER;
460 } else if (deviceTypeString != "default" && deviceTypeString != "") {
461 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
462 }
463}
464
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700465void TouchInputMapper::dumpParameters(std::string& dump) {
466 dump += INDENT3 "Parameters:\n";
467
Dominik Laskowski75788452021-02-09 18:51:25 -0800468 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700469
Dominik Laskowski75788452021-02-09 18:51:25 -0800470 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700471
472 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
473 "displayId='%s'\n",
474 toString(mParameters.hasAssociatedDisplay),
475 toString(mParameters.associatedDisplayIsExternal),
476 mParameters.uniqueDisplayId.c_str());
477 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800478 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000479 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700480 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
481 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700482}
483
484void TouchInputMapper::configureRawPointerAxes() {
485 mRawPointerAxes.clear();
486}
487
488void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
489 dump += INDENT3 "Raw Touch Axes:\n";
490 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
491 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
492 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
493 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
494 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
495 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
496 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
497 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
498 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
499 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
500 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
503}
504
505bool TouchInputMapper::hasExternalStylus() const {
506 return mExternalStylusConnected;
507}
508
509/**
510 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000511 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800512 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000513 * 3. Get the matching viewport by either unique id in idc file or by the display type
514 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800515 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700516 */
517std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800518 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000519 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800520 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700521 }
522
Christine Franks2a2293c2022-01-18 11:51:16 -0800523 const std::optional<std::string> associatedDisplayUniqueId =
524 getDeviceContext().getAssociatedDisplayUniqueId();
525 if (associatedDisplayUniqueId) {
526 return getDeviceContext().getAssociatedViewport();
527 }
528
Michael Wright227c5542020-07-02 18:30:52 +0100529 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800530 std::optional<DisplayViewport> viewport =
531 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
532 if (viewport) {
533 return viewport;
534 } else {
535 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
536 mConfig.defaultPointerDisplayId);
537 }
538 }
539
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700540 // Check if uniqueDisplayId is specified in idc file.
541 if (!mParameters.uniqueDisplayId.empty()) {
542 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
543 }
544
545 ViewportType viewportTypeToUse;
546 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100547 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700548 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100549 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700550 }
551
552 std::optional<DisplayViewport> viewport =
553 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100554 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700555 ALOGW("Input device %s should be associated with external display, "
556 "fallback to internal one for the external viewport is not found.",
557 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100558 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700559 }
560
561 return viewport;
562 }
563
564 // No associated display, return a non-display viewport.
565 DisplayViewport newViewport;
566 // Raw width and height in the natural orientation.
567 int32_t rawWidth = mRawPointerAxes.getRawWidth();
568 int32_t rawHeight = mRawPointerAxes.getRawHeight();
569 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
570 return std::make_optional(newViewport);
571}
572
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800573int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
574 if (resolution < 0) {
575 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
576 getDeviceName().c_str());
577 return 0;
578 }
579 return resolution;
580}
581
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800582void TouchInputMapper::initializeSizeRanges() {
583 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
584 mSizeScale = 0.0f;
585 return;
586 }
587
588 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000589 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800590
591 // Size factors.
592 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
593 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
594 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
595 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
596 } else {
597 mSizeScale = 0.0f;
598 }
599
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700600 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
601 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
602 .source = mSource,
603 .min = 0,
604 .max = diagonalSize,
605 .flat = 0,
606 .fuzz = 0,
607 .resolution = 0,
608 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800609
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800610 if (mRawPointerAxes.touchMajor.valid) {
611 mRawPointerAxes.touchMajor.resolution =
612 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700613 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800614 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800615
616 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700617 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800618 if (mRawPointerAxes.touchMinor.valid) {
619 mRawPointerAxes.touchMinor.resolution =
620 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700621 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800622 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800623
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700624 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
625 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
626 .source = mSource,
627 .min = 0,
628 .max = diagonalSize,
629 .flat = 0,
630 .fuzz = 0,
631 .resolution = 0,
632 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800633 if (mRawPointerAxes.toolMajor.valid) {
634 mRawPointerAxes.toolMajor.resolution =
635 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700636 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800637 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800638
639 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700640 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800641 if (mRawPointerAxes.toolMinor.valid) {
642 mRawPointerAxes.toolMinor.resolution =
643 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700644 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800645 }
646
647 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700648 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
649 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
650 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
651 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800652 } else {
653 // Support for other calibrations can be added here.
654 ALOGW("%s calibration is not supported for size ranges at the moment. "
655 "Using raw resolution instead",
656 ftl::enum_string(mCalibration.sizeCalibration).c_str());
657 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800658
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700659 mOrientedRanges.size = InputDeviceInfo::MotionRange{
660 .axis = AMOTION_EVENT_AXIS_SIZE,
661 .source = mSource,
662 .min = 0,
663 .max = 1.0,
664 .flat = 0,
665 .fuzz = 0,
666 .resolution = 0,
667 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800668}
669
670void TouchInputMapper::initializeOrientedRanges() {
671 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000672 const float orientedScaleX = mRawToDisplay.getScaleX();
673 const float orientedScaleY = mRawToDisplay.getScaleY();
674 mOrientedXPrecision = 1.0f / orientedScaleX;
675 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800676
677 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
678 mOrientedRanges.x.source = mSource;
679 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
680 mOrientedRanges.y.source = mSource;
681
682 // Scale factor for terms that are not oriented in a particular axis.
683 // If the pixels are square then xScale == yScale otherwise we fake it
684 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000685 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800686
687 initializeSizeRanges();
688
689 // Pressure factors.
690 mPressureScale = 0;
691 float pressureMax = 1.0;
692 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
693 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700694 if (mCalibration.pressureScale) {
695 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800696 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
697 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
698 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
699 }
700 }
701
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700702 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
703 .axis = AMOTION_EVENT_AXIS_PRESSURE,
704 .source = mSource,
705 .min = 0,
706 .max = pressureMax,
707 .flat = 0,
708 .fuzz = 0,
709 .resolution = 0,
710 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800711
712 // Tilt
713 mTiltXCenter = 0;
714 mTiltXScale = 0;
715 mTiltYCenter = 0;
716 mTiltYScale = 0;
717 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
718 if (mHaveTilt) {
719 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
720 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
721 mTiltXScale = M_PI / 180;
722 mTiltYScale = M_PI / 180;
723
724 if (mRawPointerAxes.tiltX.resolution) {
725 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
726 }
727 if (mRawPointerAxes.tiltY.resolution) {
728 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
729 }
730
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700731 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
732 .axis = AMOTION_EVENT_AXIS_TILT,
733 .source = mSource,
734 .min = 0,
735 .max = M_PI_2,
736 .flat = 0,
737 .fuzz = 0,
738 .resolution = 0,
739 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800740 }
741
742 // Orientation
743 mOrientationScale = 0;
744 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700745 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
746 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
747 .source = mSource,
748 .min = -M_PI,
749 .max = M_PI,
750 .flat = 0,
751 .fuzz = 0,
752 .resolution = 0,
753 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800754
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800755 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
756 if (mCalibration.orientationCalibration ==
757 Calibration::OrientationCalibration::INTERPOLATED) {
758 if (mRawPointerAxes.orientation.valid) {
759 if (mRawPointerAxes.orientation.maxValue > 0) {
760 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
761 } else if (mRawPointerAxes.orientation.minValue < 0) {
762 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
763 } else {
764 mOrientationScale = 0;
765 }
766 }
767 }
768
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700769 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
770 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
771 .source = mSource,
772 .min = -M_PI_2,
773 .max = M_PI_2,
774 .flat = 0,
775 .fuzz = 0,
776 .resolution = 0,
777 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800778 }
779
780 // Distance
781 mDistanceScale = 0;
782 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
783 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700784 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800785 }
786
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700787 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800788
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700789 .axis = AMOTION_EVENT_AXIS_DISTANCE,
790 .source = mSource,
791 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
792 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
793 .flat = 0,
794 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
795 .resolution = 0,
796 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800797 }
798
799 // Compute oriented precision, scales and ranges.
800 // Note that the maximum value reported is an inclusive maximum value so it is one
801 // unit less than the total width or height of the display.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000802 // TODO(b/20508709): Calculate the oriented ranges using the input device's raw frame.
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800803 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000804 case ui::ROTATION_90:
805 case ui::ROTATION_270:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800806 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000807 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800808 mOrientedRanges.x.flat = 0;
809 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000810 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800811
812 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000813 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800814 mOrientedRanges.y.flat = 0;
815 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000816 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800817 break;
818
819 default:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800820 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000821 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800822 mOrientedRanges.x.flat = 0;
823 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000824 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800825
826 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000827 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800828 mOrientedRanges.y.flat = 0;
829 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000830 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800831 break;
832 }
833}
834
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000835void TouchInputMapper::computeInputTransforms() {
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000836 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
837
838 ui::Size rotatedRawSize = rawSize;
839 if (mInputDeviceOrientation == ui::ROTATION_270 || mInputDeviceOrientation == ui::ROTATION_90) {
840 std::swap(rotatedRawSize.width, rotatedRawSize.height);
841 }
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000842 const auto rotationFlags = ui::Transform::toRotationFlags(-mInputDeviceOrientation);
843 mRawRotation = ui::Transform{rotationFlags};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000844
845 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
846 ui::Transform undoRawOffset;
847 undoRawOffset.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
848
849 // Step 2: Rotate the raw coordinates to the expected orientation.
850 ui::Transform rotate;
851 // When rotating raw coordinates, the raw size will be used as an offset.
852 // Account for the extra unit added to the raw range when the raw size was calculated.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000853 rotate.set(rotationFlags, rotatedRawSize.width - 1, rotatedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000854
855 // Step 3: Scale the raw coordinates to the display space.
856 ui::Transform scaleToDisplay;
857 const float xScale = static_cast<float>(mDisplayBounds.width) / rotatedRawSize.width;
858 const float yScale = static_cast<float>(mDisplayBounds.height) / rotatedRawSize.height;
859 scaleToDisplay.set(xScale, 0, 0, yScale);
860
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000861 mRawToDisplay = (scaleToDisplay * (rotate * undoRawOffset));
862
863 // Calculate the transform that takes raw coordinates to the rotated display space.
864 ui::Transform displayToRotatedDisplay;
865 displayToRotatedDisplay.set(ui::Transform::toRotationFlags(-mViewport.orientation),
866 mViewport.deviceWidth, mViewport.deviceHeight);
867 mRawToRotatedDisplay = displayToRotatedDisplay * mRawToDisplay;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000868}
869
Prabir Pradhan1728b212021-10-19 16:00:03 -0700870void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000871 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700872
873 resolveExternalStylusPresence();
874
875 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100876 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000877 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700878 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100879 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700880 if (hasStylus()) {
881 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000882 } else {
883 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700884 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800885 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700886 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100887 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700888 if (hasStylus()) {
889 mSource |= AINPUT_SOURCE_STYLUS;
890 }
891 if (hasExternalStylus()) {
892 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
893 }
Michael Wright227c5542020-07-02 18:30:52 +0100894 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700895 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100896 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700897 } else {
898 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100899 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700900 }
901
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000902 const std::optional<DisplayViewport> newViewportOpt = findViewport();
903
904 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700905 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
906 ALOGW("Touch device '%s' did not report support for X or Y axis! "
907 "The device will be inoperable.",
908 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100909 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000910 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911 ALOGI("Touch device '%s' could not query the properties of its associated "
912 "display. The device will be inoperable until the display size "
913 "becomes available.",
914 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100915 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700916 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000917 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
918 getDeviceName().c_str(), getDeviceId());
919 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000920 }
921
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700922 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000923 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000924 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
925 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
926 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
927 const float rawMeanResolution =
928 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000930 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
931 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700932 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700933 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000934 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
935 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
936 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700937
Michael Wright227c5542020-07-02 18:30:52 +0100938 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000939 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700940
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000941 mDisplayBounds = getNaturalDisplaySize(mViewport);
942 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
943 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700944
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000945 // InputReader works in the un-rotated display coordinate space, so we don't need to do
946 // anything if the device is already orientation-aware. If the device is not
947 // orientation-aware, then we need to apply the inverse rotation of the display so that
948 // when the display rotation is applied later as a part of the per-window transform, we
949 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700950 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000951 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000952 : getInverseRotation(mViewport.orientation);
953 // For orientation-aware devices that work in the un-rotated coordinate space, the
954 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000955 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000956 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700957
958 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000959 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000960 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700961 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000962 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000963 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000964 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000965 mRawToDisplay.reset();
966 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000967 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700968 }
969 }
970
971 // If moving between pointer modes, need to reset some state.
972 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
973 if (deviceModeChanged) {
974 mOrientedRanges.clear();
975 }
976
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800977 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
978 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100979 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800980 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000981 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
982 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800983 if (mPointerController == nullptr) {
984 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700985 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000986 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800987 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
988 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700989 } else {
lilinnandef700b2022-06-17 19:32:01 +0800990 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
991 !mConfig.showTouches) {
992 mPointerController->clearSpots();
993 }
Michael Wright17db18e2020-06-26 20:51:44 +0100994 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700995 }
996
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700997 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000998 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700999 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001000 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001001 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001002
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001003 configureVirtualKeys();
1004
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001005 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001006
1007 // Location
1008 updateAffineTransformation();
1009
Michael Wright227c5542020-07-02 18:30:52 +01001010 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001012 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1013 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001014
1015 // Scale movements such that one whole swipe of the touch pad covers a
1016 // given area relative to the diagonal size of the display when no acceleration
1017 // is applied.
1018 // Assume that the touch pad has a square aspect ratio such that movements in
1019 // X and Y of the same number of raw units cover the same physical distance.
1020 mPointerXMovementScale =
1021 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1022 mPointerYMovementScale = mPointerXMovementScale;
1023
1024 // Scale zooms to cover a smaller range of the display than movements do.
1025 // This value determines the area around the pointer that is affected by freeform
1026 // pointer gestures.
1027 mPointerXZoomScale =
1028 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1029 mPointerYZoomScale = mPointerXZoomScale;
1030
HQ Liue6983c72022-04-19 22:14:56 +00001031 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1032 // axis is non positive value.
1033 const float minFreeformGestureWidth =
1034 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1035
1036 mPointerGestureMaxSwipeWidth =
1037 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1038 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001039 }
1040
1041 // Inform the dispatcher about the changes.
1042 *outResetNeeded = true;
1043 bumpGeneration();
1044 }
1045}
1046
Prabir Pradhan1728b212021-10-19 16:00:03 -07001047void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001048 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001049 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001050 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1051 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001052 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053}
1054
1055void TouchInputMapper::configureVirtualKeys() {
1056 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001057 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001058
1059 mVirtualKeys.clear();
1060
1061 if (virtualKeyDefinitions.size() == 0) {
1062 return;
1063 }
1064
1065 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1066 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1067 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1068 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1069
1070 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1071 VirtualKey virtualKey;
1072
1073 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1074 int32_t keyCode;
1075 int32_t dummyKeyMetaState;
1076 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001077 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1078 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001079 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1080 continue; // drop the key
1081 }
1082
1083 virtualKey.keyCode = keyCode;
1084 virtualKey.flags = flags;
1085
1086 // convert the key definition's display coordinates into touch coordinates for a hit box
1087 int32_t halfWidth = virtualKeyDefinition.width / 2;
1088 int32_t halfHeight = virtualKeyDefinition.height / 2;
1089
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001090 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1091 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001093 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1094 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001095 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001096 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1097 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001098 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001099 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1100 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001101 touchScreenTop;
1102 mVirtualKeys.push_back(virtualKey);
1103 }
1104}
1105
1106void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1107 if (!mVirtualKeys.empty()) {
1108 dump += INDENT3 "Virtual Keys:\n";
1109
1110 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1111 const VirtualKey& virtualKey = mVirtualKeys[i];
1112 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1113 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1114 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1115 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1116 }
1117 }
1118}
1119
1120void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001121 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001122 Calibration& out = mCalibration;
1123
1124 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001125 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001126 std::string sizeCalibrationString;
1127 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001129 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001130 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001131 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001133 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001134 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001135 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001137 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001139 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001140 }
1141 }
1142
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001143 float sizeScale;
1144
1145 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1146 out.sizeScale = sizeScale;
1147 }
1148 float sizeBias;
1149 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1150 out.sizeBias = sizeBias;
1151 }
1152 bool sizeIsSummed;
1153 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1154 out.sizeIsSummed = sizeIsSummed;
1155 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001156
1157 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001158 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001159 std::string pressureCalibrationString;
1160 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001161 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001163 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001164 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 } else if (pressureCalibrationString != "default") {
1168 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001169 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 }
1171 }
1172
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001173 float pressureScale;
1174 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1175 out.pressureScale = pressureScale;
1176 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177
1178 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001180 std::string orientationCalibrationString;
1181 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (orientationCalibrationString != "default") {
1189 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001190 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 }
1192 }
1193
1194 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001196 std::string distanceCalibrationString;
1197 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 } else if (distanceCalibrationString != "default") {
1203 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001204 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 }
1206 }
1207
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001208 float distanceScale;
1209 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1210 out.distanceScale = distanceScale;
1211 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001214 std::string coverageCalibrationString;
1215 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001218 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001219 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 } else if (coverageCalibrationString != "default") {
1221 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001222 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 }
1224 }
1225}
1226
1227void TouchInputMapper::resolveCalibration() {
1228 // Size
1229 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001230 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1231 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 }
1233 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001234 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235 }
1236
1237 // Pressure
1238 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001239 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1240 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001243 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 }
1245
1246 // Orientation
1247 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001248 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1249 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001252 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 }
1254
1255 // Distance
1256 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001257 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1258 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001261 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263
1264 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001265 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1266 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 }
1268}
1269
1270void TouchInputMapper::dumpCalibration(std::string& dump) {
1271 dump += INDENT3 "Calibration:\n";
1272
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001273 dump += INDENT4 "touch.size.calibration: ";
1274 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001276 if (mCalibration.sizeScale) {
1277 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 }
1279
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001280 if (mCalibration.sizeBias) {
1281 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 }
1283
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001284 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001286 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 }
1288
1289 // Pressure
1290 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001291 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 dump += INDENT4 "touch.pressure.calibration: none\n";
1293 break;
Michael Wright227c5542020-07-02 18:30:52 +01001294 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 dump += INDENT4 "touch.pressure.calibration: physical\n";
1296 break;
Michael Wright227c5542020-07-02 18:30:52 +01001297 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1299 break;
1300 default:
1301 ALOG_ASSERT(false);
1302 }
1303
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001304 if (mCalibration.pressureScale) {
1305 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 }
1307
1308 // Orientation
1309 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001310 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 dump += INDENT4 "touch.orientation.calibration: none\n";
1312 break;
Michael Wright227c5542020-07-02 18:30:52 +01001313 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1315 break;
Michael Wright227c5542020-07-02 18:30:52 +01001316 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 dump += INDENT4 "touch.orientation.calibration: vector\n";
1318 break;
1319 default:
1320 ALOG_ASSERT(false);
1321 }
1322
1323 // Distance
1324 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001325 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 dump += INDENT4 "touch.distance.calibration: none\n";
1327 break;
Michael Wright227c5542020-07-02 18:30:52 +01001328 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 dump += INDENT4 "touch.distance.calibration: scaled\n";
1330 break;
1331 default:
1332 ALOG_ASSERT(false);
1333 }
1334
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001335 if (mCalibration.distanceScale) {
1336 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 }
1338
1339 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001340 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.coverage.calibration: none\n";
1342 break;
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.coverage.calibration: box\n";
1345 break;
1346 default:
1347 ALOG_ASSERT(false);
1348 }
1349}
1350
1351void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1352 dump += INDENT3 "Affine Transformation:\n";
1353
1354 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1355 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1356 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1357 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1358 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1359 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1360}
1361
1362void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001363 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001364 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001365}
1366
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001367std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001368 std::list<NotifyArgs> out = cancelTouch(when, when);
1369 updateTouchSpots();
1370
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001371 mCursorButtonAccumulator.reset(getDeviceContext());
1372 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001373 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374
1375 mPointerVelocityControl.reset();
1376 mWheelXVelocityControl.reset();
1377 mWheelYVelocityControl.reset();
1378
1379 mRawStatesPending.clear();
1380 mCurrentRawState.clear();
1381 mCurrentCookedState.clear();
1382 mLastRawState.clear();
1383 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001384 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001385 mSentHoverEnter = false;
1386 mHavePointerIds = false;
1387 mCurrentMotionAborted = false;
1388 mDownTime = 0;
1389
1390 mCurrentVirtualKey.down = false;
1391
1392 mPointerGesture.reset();
1393 mPointerSimple.reset();
1394 resetExternalStylus();
1395
1396 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001397 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001398 mPointerController->clearSpots();
1399 }
1400
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001401 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001402}
1403
1404void TouchInputMapper::resetExternalStylus() {
1405 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001406 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407 mExternalStylusFusionTimeout = LLONG_MAX;
1408 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001409 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410}
1411
1412void TouchInputMapper::clearStylusDataPendingFlags() {
1413 mExternalStylusDataPending = false;
1414 mExternalStylusFusionTimeout = LLONG_MAX;
1415}
1416
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001417std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001418 mCursorButtonAccumulator.process(rawEvent);
1419 mCursorScrollAccumulator.process(rawEvent);
1420 mTouchButtonAccumulator.process(rawEvent);
1421
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001422 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001424 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001425 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001426 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427}
1428
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001429std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1430 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001431 if (mDeviceMode == DeviceMode::DISABLED) {
1432 // Only save the last pending state when the device is disabled.
1433 mRawStatesPending.clear();
1434 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001435 // Push a new state.
1436 mRawStatesPending.emplace_back();
1437
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001438 RawState& next = mRawStatesPending.back();
1439 next.clear();
1440 next.when = when;
1441 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001442
1443 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001444 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001445 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1446
1447 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001448 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1449 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001450 mCursorScrollAccumulator.finishSync();
1451
1452 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001453 syncTouch(when, &next);
1454
1455 // The last RawState is the actually second to last, since we just added a new state
1456 const RawState& last =
1457 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001458
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001459 std::tie(next.when, next.readTime) =
1460 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1461 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001462
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001463 // Assign pointer ids.
1464 if (!mHavePointerIds) {
1465 assignPointerIds(last, next);
1466 }
1467
Harry Cutts45483602022-08-24 14:36:48 +00001468 ALOGD_IF(DEBUG_RAW_EVENTS,
1469 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1470 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1471 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1472 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1473 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1474 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001475
Arthur Hung9ad18942021-06-19 02:04:46 +00001476 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1477 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1478 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1479 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1480 next.rawPointerData.hoveringIdBits.value);
1481 }
1482
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001483 out += processRawTouches(false /*timeout*/);
1484 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485}
1486
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001487std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1488 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001489 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001490 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001491 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001492 }
1493
1494 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1495 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1496 // touching the current state will only observe the events that have been dispatched to the
1497 // rest of the pipeline.
1498 const size_t N = mRawStatesPending.size();
1499 size_t count;
1500 for (count = 0; count < N; count++) {
1501 const RawState& next = mRawStatesPending[count];
1502
1503 // A failure to assign the stylus id means that we're waiting on stylus data
1504 // and so should defer the rest of the pipeline.
1505 if (assignExternalStylusId(next, timeout)) {
1506 break;
1507 }
1508
1509 // All ready to go.
1510 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001511 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001512 if (mCurrentRawState.when < mLastRawState.when) {
1513 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001514 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001515 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001516 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 }
1518 if (count != 0) {
1519 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1520 }
1521
1522 if (mExternalStylusDataPending) {
1523 if (timeout) {
1524 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1525 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001526 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001527 ALOGD_IF(DEBUG_STYLUS_FUSION,
1528 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001529 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001530 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001531 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1532 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1533 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1534 }
1535 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001536 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001537}
1538
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001539std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1540 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001541 // Always start with a clean state.
1542 mCurrentCookedState.clear();
1543
1544 // Apply stylus buttons to current raw state.
1545 applyExternalStylusButtonState(when);
1546
1547 // Handle policy on initial down or hover events.
1548 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1549 mCurrentRawState.rawPointerData.pointerCount != 0;
1550
1551 uint32_t policyFlags = 0;
1552 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1553 if (initialDown || buttonsPressed) {
1554 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001555 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001556 getContext()->fadePointer();
1557 }
1558
1559 if (mParameters.wake) {
1560 policyFlags |= POLICY_FLAG_WAKE;
1561 }
1562 }
1563
1564 // Consume raw off-screen touches before cooking pointer data.
1565 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001566 bool consumed;
1567 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1568 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001569 mCurrentRawState.rawPointerData.clear();
1570 }
1571
1572 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1573 // with cooked pointer data that has the same ids and indices as the raw data.
1574 // The following code can use either the raw or cooked data, as needed.
1575 cookPointerData();
1576
1577 // Apply stylus pressure to current cooked state.
1578 applyExternalStylusTouchState(when);
1579
1580 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001581 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1582 mSource, mViewport.displayId, policyFlags,
1583 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001584
1585 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001586 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001587 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1588 uint32_t id = idBits.clearFirstMarkedBit();
1589 const RawPointerData::Pointer& pointer =
1590 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001591 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592 mCurrentCookedState.stylusIdBits.markBit(id);
1593 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1594 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1595 mCurrentCookedState.fingerIdBits.markBit(id);
1596 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1597 mCurrentCookedState.mouseIdBits.markBit(id);
1598 }
1599 }
1600 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1601 uint32_t id = idBits.clearFirstMarkedBit();
1602 const RawPointerData::Pointer& pointer =
1603 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001604 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001605 mCurrentCookedState.stylusIdBits.markBit(id);
1606 }
1607 }
1608
1609 // Stylus takes precedence over all tools, then mouse, then finger.
1610 PointerUsage pointerUsage = mPointerUsage;
1611 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1612 mCurrentCookedState.mouseIdBits.clear();
1613 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001614 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1616 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001617 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001618 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1619 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001620 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001621 }
1622
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001623 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001626 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001627 out += dispatchButtonRelease(when, readTime, policyFlags);
1628 out += dispatchHoverExit(when, readTime, policyFlags);
1629 out += dispatchTouches(when, readTime, policyFlags);
1630 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1631 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 }
1633
1634 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1635 mCurrentMotionAborted = false;
1636 }
1637 }
1638
1639 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001640 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1641 mSource, mViewport.displayId, policyFlags,
1642 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001643
1644 // Clear some transient state.
1645 mCurrentRawState.rawVScroll = 0;
1646 mCurrentRawState.rawHScroll = 0;
1647
1648 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001649 mLastRawState = mCurrentRawState;
1650 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001651 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001652}
1653
Garfield Tanc734e4f2021-01-15 20:01:39 -08001654void TouchInputMapper::updateTouchSpots() {
1655 if (!mConfig.showTouches || mPointerController == nullptr) {
1656 return;
1657 }
1658
1659 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1660 // clear touch spots.
1661 if (mDeviceMode != DeviceMode::DIRECT &&
1662 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1663 return;
1664 }
1665
1666 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1667 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1668
1669 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001670 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1671 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001672 mCurrentCookedState.cookedPointerData.touchingIdBits,
1673 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001674}
1675
1676bool TouchInputMapper::isTouchScreen() {
1677 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1678 mParameters.hasAssociatedDisplay;
1679}
1680
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001681void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001682 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1683 // If any of the external buttons are already pressed by the touch device, ignore them.
1684 const int32_t pressedButtons = ~mCurrentRawState.buttonState & mExternalStylusState.buttons;
1685 const int32_t releasedButtons =
1686 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1687
1688 mCurrentRawState.buttonState |= pressedButtons;
1689 mCurrentRawState.buttonState &= ~releasedButtons;
1690
1691 mExternalStylusButtonsApplied |= pressedButtons;
1692 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001693 }
1694}
1695
1696void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1697 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1698 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001699 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1700 return;
1701 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001702
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001703 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1704 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1705 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1706 : 0.f;
1707 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1708 pressure = *mExternalStylusState.pressure;
1709 }
1710 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1711 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001712
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001713 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001715 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001716 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001717 }
1718}
1719
1720bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001721 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001722 return false;
1723 }
1724
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001725 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001726 if (mFusedStylusPointerId &&
1727 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001728 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001729 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001730 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001731 }
1732
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001733 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1734 state.rawPointerData.pointerCount != 0;
1735 if (!initialDown) {
1736 return false;
1737 }
1738
1739 if (!mExternalStylusState.pressure) {
1740 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1741 return false;
1742 }
1743
1744 if (*mExternalStylusState.pressure != 0.0f) {
1745 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1746 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1747 return false;
1748 }
1749
1750 if (timeout) {
1751 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1752 mFusedStylusPointerId.reset();
1753 mExternalStylusFusionTimeout = LLONG_MAX;
1754 return false;
1755 }
1756
1757 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1758 // being processed until we either get pressure data or timeout.
1759 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1760 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1761 }
1762 ALOGD_IF(DEBUG_STYLUS_FUSION,
1763 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1764 mExternalStylusFusionTimeout);
1765 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1766 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001767}
1768
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001769std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1770 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001771 if (mDeviceMode == DeviceMode::POINTER) {
1772 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001773 // Since this is a synthetic event, we can consider its latency to be zero
1774 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001775 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001776 }
Michael Wright227c5542020-07-02 18:30:52 +01001777 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001778 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001779 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1781 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1782 }
1783 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001784 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001785}
1786
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001787std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1788 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001789 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001790 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001791 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001792 // The following three cases are handled here:
1793 // - We're in the middle of a fused stream of data;
1794 // - We're waiting on external stylus data before dispatching the initial down; or
1795 // - Only the button state, which is not reported through a specific pointer, has changed.
1796 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001797 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001798 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001799 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001800 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001801}
1802
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001803std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1804 uint32_t policyFlags, bool& outConsumed) {
1805 outConsumed = false;
1806 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001807 // Check for release of a virtual key.
1808 if (mCurrentVirtualKey.down) {
1809 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1810 // Pointer went up while virtual key was down.
1811 mCurrentVirtualKey.down = false;
1812 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001813 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1814 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1815 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001816 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1817 AKEY_EVENT_FLAG_FROM_SYSTEM |
1818 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001819 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001820 outConsumed = true;
1821 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001822 }
1823
1824 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1825 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1826 const RawPointerData::Pointer& pointer =
1827 mCurrentRawState.rawPointerData.pointerForId(id);
1828 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1829 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1830 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001831 outConsumed = true;
1832 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001833 }
1834 }
1835
1836 // Pointer left virtual key area or another pointer also went down.
1837 // Send key cancellation but do not consume the touch yet.
1838 // This is useful when the user swipes through from the virtual key area
1839 // into the main display surface.
1840 mCurrentVirtualKey.down = false;
1841 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001842 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1843 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001844 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1845 AKEY_EVENT_FLAG_FROM_SYSTEM |
1846 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1847 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001848 }
1849 }
1850
1851 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1852 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1853 // Pointer just went down. Check for virtual key press or off-screen touches.
1854 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1855 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001856 // Skip checking whether the pointer is inside the physical frame if the device is in
1857 // unscaled mode.
1858 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1859 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001860 // If exactly one pointer went down, check for virtual key hit.
1861 // Otherwise we will drop the entire stroke.
1862 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1863 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1864 if (virtualKey) {
1865 mCurrentVirtualKey.down = true;
1866 mCurrentVirtualKey.downTime = when;
1867 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1868 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1869 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001870 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1871 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001872
1873 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001874 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1875 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1876 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001877 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1878 AKEY_EVENT_ACTION_DOWN,
1879 AKEY_EVENT_FLAG_FROM_SYSTEM |
1880 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001881 }
1882 }
1883 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001884 outConsumed = true;
1885 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001886 }
1887 }
1888
1889 // Disable all virtual key touches that happen within a short time interval of the
1890 // most recent touch within the screen area. The idea is to filter out stray
1891 // virtual key presses when interacting with the touch screen.
1892 //
1893 // Problems we're trying to solve:
1894 //
1895 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1896 // virtual key area that is implemented by a separate touch panel and accidentally
1897 // triggers a virtual key.
1898 //
1899 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1900 // area and accidentally triggers a virtual key. This often happens when virtual keys
1901 // are layed out below the screen near to where the on screen keyboard's space bar
1902 // is displayed.
1903 if (mConfig.virtualKeyQuietTime > 0 &&
1904 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001905 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001906 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001907 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001908}
1909
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001910NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1911 uint32_t policyFlags, int32_t keyEventAction,
1912 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001913 int32_t keyCode = mCurrentVirtualKey.keyCode;
1914 int32_t scanCode = mCurrentVirtualKey.scanCode;
1915 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001916 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001917 policyFlags |= POLICY_FLAG_VIRTUAL;
1918
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001919 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1920 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1921 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001922}
1923
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001924std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1925 uint32_t policyFlags) {
1926 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001927 if (mCurrentMotionAborted) {
1928 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001929 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001930 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001931 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1932 if (!currentIdBits.isEmpty()) {
1933 int32_t metaState = getContext()->getGlobalMetaState();
1934 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001935 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001936 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1937 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001938 mCurrentCookedState.cookedPointerData.pointerProperties,
1939 mCurrentCookedState.cookedPointerData.pointerCoords,
1940 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1941 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1942 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001943 mCurrentMotionAborted = true;
1944 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001945 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001946}
1947
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001948// Updates pointer coords and properties for pointers with specified ids that have moved.
1949// Returns true if any of them changed.
1950static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1951 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1952 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1953 BitSet32 idBits) {
1954 bool changed = false;
1955 while (!idBits.isEmpty()) {
1956 uint32_t id = idBits.clearFirstMarkedBit();
1957 uint32_t inIndex = inIdToIndex[id];
1958 uint32_t outIndex = outIdToIndex[id];
1959
1960 const PointerProperties& curInProperties = inProperties[inIndex];
1961 const PointerCoords& curInCoords = inCoords[inIndex];
1962 PointerProperties& curOutProperties = outProperties[outIndex];
1963 PointerCoords& curOutCoords = outCoords[outIndex];
1964
1965 if (curInProperties != curOutProperties) {
1966 curOutProperties.copyFrom(curInProperties);
1967 changed = true;
1968 }
1969
1970 if (curInCoords != curOutCoords) {
1971 curOutCoords.copyFrom(curInCoords);
1972 changed = true;
1973 }
1974 }
1975 return changed;
1976}
1977
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001978std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1979 uint32_t policyFlags) {
1980 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001981 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1982 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1983 int32_t metaState = getContext()->getGlobalMetaState();
1984 int32_t buttonState = mCurrentCookedState.buttonState;
1985
1986 if (currentIdBits == lastIdBits) {
1987 if (!currentIdBits.isEmpty()) {
1988 // No pointer id changes so this is a move event.
1989 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001990 out.push_back(
1991 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1992 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1993 mCurrentCookedState.cookedPointerData.pointerProperties,
1994 mCurrentCookedState.cookedPointerData.pointerCoords,
1995 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1996 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1997 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001998 }
1999 } else {
2000 // There may be pointers going up and pointers going down and pointers moving
2001 // all at the same time.
2002 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2003 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2004 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2005 BitSet32 dispatchedIdBits(lastIdBits.value);
2006
2007 // Update last coordinates of pointers that have moved so that we observe the new
2008 // pointer positions at the same time as other pointers that have just gone up.
2009 bool moveNeeded =
2010 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2011 mCurrentCookedState.cookedPointerData.pointerCoords,
2012 mCurrentCookedState.cookedPointerData.idToIndex,
2013 mLastCookedState.cookedPointerData.pointerProperties,
2014 mLastCookedState.cookedPointerData.pointerCoords,
2015 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2016 if (buttonState != mLastCookedState.buttonState) {
2017 moveNeeded = true;
2018 }
2019
2020 // Dispatch pointer up events.
2021 while (!upIdBits.isEmpty()) {
2022 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002023 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002024 if (isCanceled) {
2025 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2026 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002027 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2028 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2029 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2030 buttonState, 0,
2031 mLastCookedState.cookedPointerData.pointerProperties,
2032 mLastCookedState.cookedPointerData.pointerCoords,
2033 mLastCookedState.cookedPointerData.idToIndex,
2034 dispatchedIdBits, upId, mOrientedXPrecision,
2035 mOrientedYPrecision, mDownTime,
2036 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002037 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002038 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002039 }
2040
2041 // Dispatch move events if any of the remaining pointers moved from their old locations.
2042 // Although applications receive new locations as part of individual pointer up
2043 // events, they do not generally handle them except when presented in a move event.
2044 if (moveNeeded && !moveIdBits.isEmpty()) {
2045 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002046 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2047 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2048 mCurrentCookedState.cookedPointerData.pointerProperties,
2049 mCurrentCookedState.cookedPointerData.pointerCoords,
2050 mCurrentCookedState.cookedPointerData.idToIndex,
2051 dispatchedIdBits, -1, mOrientedXPrecision,
2052 mOrientedYPrecision, mDownTime,
2053 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002054 }
2055
2056 // Dispatch pointer down events using the new pointer locations.
2057 while (!downIdBits.isEmpty()) {
2058 uint32_t downId = downIdBits.clearFirstMarkedBit();
2059 dispatchedIdBits.markBit(downId);
2060
2061 if (dispatchedIdBits.count() == 1) {
2062 // First pointer is going down. Set down time.
2063 mDownTime = when;
2064 }
2065
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002066 out.push_back(
2067 dispatchMotion(when, readTime, policyFlags, mSource,
2068 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2069 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2070 mCurrentCookedState.cookedPointerData.pointerCoords,
2071 mCurrentCookedState.cookedPointerData.idToIndex,
2072 dispatchedIdBits, downId, mOrientedXPrecision,
2073 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002074 }
2075 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002076 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002077}
2078
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002079std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2080 uint32_t policyFlags) {
2081 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002082 if (mSentHoverEnter &&
2083 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2084 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2085 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002086 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2087 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2088 mLastCookedState.buttonState, 0,
2089 mLastCookedState.cookedPointerData.pointerProperties,
2090 mLastCookedState.cookedPointerData.pointerCoords,
2091 mLastCookedState.cookedPointerData.idToIndex,
2092 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2093 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2094 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002095 mSentHoverEnter = false;
2096 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002097 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002098}
2099
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002100std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2101 uint32_t policyFlags) {
2102 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002103 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2104 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2105 int32_t metaState = getContext()->getGlobalMetaState();
2106 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002107 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2108 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2109 mCurrentRawState.buttonState, 0,
2110 mCurrentCookedState.cookedPointerData.pointerProperties,
2111 mCurrentCookedState.cookedPointerData.pointerCoords,
2112 mCurrentCookedState.cookedPointerData.idToIndex,
2113 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2114 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2115 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002116 mSentHoverEnter = true;
2117 }
2118
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002119 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2120 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2121 mCurrentRawState.buttonState, 0,
2122 mCurrentCookedState.cookedPointerData.pointerProperties,
2123 mCurrentCookedState.cookedPointerData.pointerCoords,
2124 mCurrentCookedState.cookedPointerData.idToIndex,
2125 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2126 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2127 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002128 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002129 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002130}
2131
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002132std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2133 uint32_t policyFlags) {
2134 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002135 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2136 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2137 const int32_t metaState = getContext()->getGlobalMetaState();
2138 int32_t buttonState = mLastCookedState.buttonState;
2139 while (!releasedButtons.isEmpty()) {
2140 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2141 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002142 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2143 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2144 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002145 mLastCookedState.cookedPointerData.pointerProperties,
2146 mLastCookedState.cookedPointerData.pointerCoords,
2147 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002148 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2149 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002150 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002151 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002152}
2153
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002154std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2155 uint32_t policyFlags) {
2156 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2158 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2159 const int32_t metaState = getContext()->getGlobalMetaState();
2160 int32_t buttonState = mLastCookedState.buttonState;
2161 while (!pressedButtons.isEmpty()) {
2162 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2163 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002164 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2165 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2166 buttonState, 0,
2167 mCurrentCookedState.cookedPointerData.pointerProperties,
2168 mCurrentCookedState.cookedPointerData.pointerCoords,
2169 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2170 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2171 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002172 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002173 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002174}
2175
2176const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2177 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2178 return cookedPointerData.touchingIdBits;
2179 }
2180 return cookedPointerData.hoveringIdBits;
2181}
2182
2183void TouchInputMapper::cookPointerData() {
2184 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2185
2186 mCurrentCookedState.cookedPointerData.clear();
2187 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2188 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2189 mCurrentRawState.rawPointerData.hoveringIdBits;
2190 mCurrentCookedState.cookedPointerData.touchingIdBits =
2191 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002192 mCurrentCookedState.cookedPointerData.canceledIdBits =
2193 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002194
2195 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2196 mCurrentCookedState.buttonState = 0;
2197 } else {
2198 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2199 }
2200
2201 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002202 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002203 for (uint32_t i = 0; i < currentPointerCount; i++) {
2204 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2205
2206 // Size
2207 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2208 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002209 case Calibration::SizeCalibration::GEOMETRIC:
2210 case Calibration::SizeCalibration::DIAMETER:
2211 case Calibration::SizeCalibration::BOX:
2212 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002213 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2214 touchMajor = in.touchMajor;
2215 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2216 toolMajor = in.toolMajor;
2217 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2218 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2219 : in.touchMajor;
2220 } else if (mRawPointerAxes.touchMajor.valid) {
2221 toolMajor = touchMajor = in.touchMajor;
2222 toolMinor = touchMinor =
2223 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2224 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2225 : in.touchMajor;
2226 } else if (mRawPointerAxes.toolMajor.valid) {
2227 touchMajor = toolMajor = in.toolMajor;
2228 touchMinor = toolMinor =
2229 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2230 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2231 : in.toolMajor;
2232 } else {
2233 ALOG_ASSERT(false,
2234 "No touch or tool axes. "
2235 "Size calibration should have been resolved to NONE.");
2236 touchMajor = 0;
2237 touchMinor = 0;
2238 toolMajor = 0;
2239 toolMinor = 0;
2240 size = 0;
2241 }
2242
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002243 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2245 if (touchingCount > 1) {
2246 touchMajor /= touchingCount;
2247 touchMinor /= touchingCount;
2248 toolMajor /= touchingCount;
2249 toolMinor /= touchingCount;
2250 size /= touchingCount;
2251 }
2252 }
2253
Michael Wright227c5542020-07-02 18:30:52 +01002254 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002255 touchMajor *= mGeometricScale;
2256 touchMinor *= mGeometricScale;
2257 toolMajor *= mGeometricScale;
2258 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002259 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002260 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2261 touchMinor = touchMajor;
2262 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2263 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002264 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002265 touchMinor = touchMajor;
2266 toolMinor = toolMajor;
2267 }
2268
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002269 mCalibration.applySizeScaleAndBias(touchMajor);
2270 mCalibration.applySizeScaleAndBias(touchMinor);
2271 mCalibration.applySizeScaleAndBias(toolMajor);
2272 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002273 size *= mSizeScale;
2274 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002275 case Calibration::SizeCalibration::DEFAULT:
2276 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2277 break;
2278 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002279 touchMajor = 0;
2280 touchMinor = 0;
2281 toolMajor = 0;
2282 toolMinor = 0;
2283 size = 0;
2284 break;
2285 }
2286
2287 // Pressure
2288 float pressure;
2289 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002290 case Calibration::PressureCalibration::PHYSICAL:
2291 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 pressure = in.pressure * mPressureScale;
2293 break;
2294 default:
2295 pressure = in.isHovering ? 0 : 1;
2296 break;
2297 }
2298
2299 // Tilt and Orientation
2300 float tilt;
2301 float orientation;
2302 if (mHaveTilt) {
2303 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2304 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002305 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002306 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2307 } else {
2308 tilt = 0;
2309
2310 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002311 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002312 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002313 break;
Michael Wright227c5542020-07-02 18:30:52 +01002314 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2316 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2317 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002318 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002319 float confidence = hypotf(c1, c2);
2320 float scale = 1.0f + confidence / 16.0f;
2321 touchMajor *= scale;
2322 touchMinor /= scale;
2323 toolMajor *= scale;
2324 toolMinor /= scale;
2325 } else {
2326 orientation = 0;
2327 }
2328 break;
2329 }
2330 default:
2331 orientation = 0;
2332 }
2333 }
2334
2335 // Distance
2336 float distance;
2337 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002338 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339 distance = in.distance * mDistanceScale;
2340 break;
2341 default:
2342 distance = 0;
2343 }
2344
2345 // Coverage
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002346 Rect rawCoverage{0, 0};
2347 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
2348 rawCoverage.left = (in.toolMinor & 0xffff0000) >> 16;
2349 rawCoverage.right = in.toolMinor & 0x0000ffff;
2350 rawCoverage.bottom = in.toolMajor & 0x0000ffff;
2351 rawCoverage.top = (in.toolMajor & 0xffff0000) >> 16;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 }
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002353 const auto coverage = mRawToDisplay.transform(rawCoverage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002355 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2356 vec2 transformed = {in.x, in.y};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002357 // TODO: Adjust coverage coords?
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002358 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2359 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002360
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 // Write output coords.
2362 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2363 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002364 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2365 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2367 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2368 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2369 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2370 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2371 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2372 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002373 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002374 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, coverage.left);
2375 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, coverage.top);
2376 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, coverage.right);
2377 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, coverage.bottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 } else {
2379 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2380 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2381 }
2382
Chris Ye364fdb52020-08-05 15:07:56 -07002383 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002384 uint32_t id = in.id;
2385 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2386 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2387 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002388 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2389 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002390 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2391 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2392 }
2393
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 // Write output properties.
2395 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 properties.clear();
2397 properties.id = id;
2398 properties.toolType = in.toolType;
2399
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002400 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002401 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002402 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 }
2404}
2405
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002406std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2407 uint32_t policyFlags,
2408 PointerUsage pointerUsage) {
2409 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002411 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002412 mPointerUsage = pointerUsage;
2413 }
2414
2415 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002416 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002417 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 break;
Michael Wright227c5542020-07-02 18:30:52 +01002419 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002420 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002421 break;
Michael Wright227c5542020-07-02 18:30:52 +01002422 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002423 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002424 break;
Michael Wright227c5542020-07-02 18:30:52 +01002425 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 break;
2427 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002428 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429}
2430
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002431std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2432 uint32_t policyFlags) {
2433 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002435 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002436 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002437 break;
Michael Wright227c5542020-07-02 18:30:52 +01002438 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002439 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 break;
Michael Wright227c5542020-07-02 18:30:52 +01002441 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002442 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 break;
Michael Wright227c5542020-07-02 18:30:52 +01002444 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 break;
2446 }
2447
Michael Wright227c5542020-07-02 18:30:52 +01002448 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002449 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450}
2451
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002452std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2453 uint32_t policyFlags,
2454 bool isTimeout) {
2455 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 // Update current gesture coordinates.
2457 bool cancelPreviousGesture, finishPreviousGesture;
2458 bool sendEvents =
2459 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2460 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002461 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462 }
2463 if (finishPreviousGesture) {
2464 cancelPreviousGesture = false;
2465 }
2466
2467 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002468 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002469 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 if (finishPreviousGesture || cancelPreviousGesture) {
2471 mPointerController->clearSpots();
2472 }
2473
Michael Wright227c5542020-07-02 18:30:52 +01002474 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002475 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2476 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002477 mPointerGesture.currentGestureIdBits,
2478 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 }
2480 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002481 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002482 }
2483
2484 // Show or hide the pointer if needed.
2485 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002486 case PointerGesture::Mode::NEUTRAL:
2487 case PointerGesture::Mode::QUIET:
2488 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2489 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002491 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002492 }
2493 break;
Michael Wright227c5542020-07-02 18:30:52 +01002494 case PointerGesture::Mode::TAP:
2495 case PointerGesture::Mode::TAP_DRAG:
2496 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2497 case PointerGesture::Mode::HOVER:
2498 case PointerGesture::Mode::PRESS:
2499 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002500 // Unfade the pointer when the current gesture manipulates the
2501 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002502 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 break;
Michael Wright227c5542020-07-02 18:30:52 +01002504 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002505 // Fade the pointer when the current gesture manipulates a different
2506 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002507 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002508 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002510 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 }
2512 break;
2513 }
2514
2515 // Send events!
2516 int32_t metaState = getContext()->getGlobalMetaState();
2517 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002518 const MotionClassification classification =
2519 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2520 ? MotionClassification::TWO_FINGER_SWIPE
2521 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002523 uint32_t flags = 0;
2524
2525 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2526 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2527 }
2528
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002529 // Update last coordinates of pointers that have moved so that we observe the new
2530 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002531 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2532 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2533 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2534 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2535 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2536 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002537 bool moveNeeded = false;
2538 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2539 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2540 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2541 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2542 mPointerGesture.lastGestureIdBits.value);
2543 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2544 mPointerGesture.currentGestureCoords,
2545 mPointerGesture.currentGestureIdToIndex,
2546 mPointerGesture.lastGestureProperties,
2547 mPointerGesture.lastGestureCoords,
2548 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2549 if (buttonState != mLastCookedState.buttonState) {
2550 moveNeeded = true;
2551 }
2552 }
2553
2554 // Send motion events for all pointers that went up or were canceled.
2555 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2556 if (!dispatchedGestureIdBits.isEmpty()) {
2557 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002558 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002559 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002560 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002561 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2562 mPointerGesture.lastGestureProperties,
2563 mPointerGesture.lastGestureCoords,
2564 mPointerGesture.lastGestureIdToIndex,
2565 dispatchedGestureIdBits, -1, 0, 0,
2566 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002567
2568 dispatchedGestureIdBits.clear();
2569 } else {
2570 BitSet32 upGestureIdBits;
2571 if (finishPreviousGesture) {
2572 upGestureIdBits = dispatchedGestureIdBits;
2573 } else {
2574 upGestureIdBits.value =
2575 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2576 }
2577 while (!upGestureIdBits.isEmpty()) {
2578 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2579
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002580 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2581 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2582 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2583 mPointerGesture.lastGestureProperties,
2584 mPointerGesture.lastGestureCoords,
2585 mPointerGesture.lastGestureIdToIndex,
2586 dispatchedGestureIdBits, id, 0, 0,
2587 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002588
2589 dispatchedGestureIdBits.clearBit(id);
2590 }
2591 }
2592 }
2593
2594 // Send motion events for all pointers that moved.
2595 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002596 out.push_back(
2597 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2598 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2599 mPointerGesture.currentGestureProperties,
2600 mPointerGesture.currentGestureCoords,
2601 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2602 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002603 }
2604
2605 // Send motion events for all pointers that went down.
2606 if (down) {
2607 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2608 ~dispatchedGestureIdBits.value);
2609 while (!downGestureIdBits.isEmpty()) {
2610 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2611 dispatchedGestureIdBits.markBit(id);
2612
2613 if (dispatchedGestureIdBits.count() == 1) {
2614 mPointerGesture.downTime = when;
2615 }
2616
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002617 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2618 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2619 buttonState, 0, mPointerGesture.currentGestureProperties,
2620 mPointerGesture.currentGestureCoords,
2621 mPointerGesture.currentGestureIdToIndex,
2622 dispatchedGestureIdBits, id, 0, 0,
2623 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002624 }
2625 }
2626
2627 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002628 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002629 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2630 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2631 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2632 mPointerGesture.currentGestureProperties,
2633 mPointerGesture.currentGestureCoords,
2634 mPointerGesture.currentGestureIdToIndex,
2635 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2636 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002637 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2638 // Synthesize a hover move event after all pointers go up to indicate that
2639 // the pointer is hovering again even if the user is not currently touching
2640 // the touch pad. This ensures that a view will receive a fresh hover enter
2641 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002642 float x, y;
2643 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002644
2645 PointerProperties pointerProperties;
2646 pointerProperties.clear();
2647 pointerProperties.id = 0;
2648 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2649
2650 PointerCoords pointerCoords;
2651 pointerCoords.clear();
2652 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2653 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2654
2655 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002656 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2657 mSource, displayId, policyFlags,
2658 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2659 buttonState, MotionClassification::NONE,
2660 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2661 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2662 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002663 }
2664
2665 // Update state.
2666 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2667 if (!down) {
2668 mPointerGesture.lastGestureIdBits.clear();
2669 } else {
2670 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2671 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2672 uint32_t id = idBits.clearFirstMarkedBit();
2673 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2674 mPointerGesture.lastGestureProperties[index].copyFrom(
2675 mPointerGesture.currentGestureProperties[index]);
2676 mPointerGesture.lastGestureCoords[index].copyFrom(
2677 mPointerGesture.currentGestureCoords[index]);
2678 mPointerGesture.lastGestureIdToIndex[id] = index;
2679 }
2680 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002681 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002682}
2683
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002684std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2685 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002686 const MotionClassification classification =
2687 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2688 ? MotionClassification::TWO_FINGER_SWIPE
2689 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002690 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002691 // Cancel previously dispatches pointers.
2692 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2693 int32_t metaState = getContext()->getGlobalMetaState();
2694 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002695 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002696 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2697 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002698 mPointerGesture.lastGestureProperties,
2699 mPointerGesture.lastGestureCoords,
2700 mPointerGesture.lastGestureIdToIndex,
2701 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2702 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002703 }
2704
2705 // Reset the current pointer gesture.
2706 mPointerGesture.reset();
2707 mPointerVelocityControl.reset();
2708
2709 // Remove any current spots.
2710 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002711 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002712 mPointerController->clearSpots();
2713 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002714 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002715}
2716
2717bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2718 bool* outFinishPreviousGesture, bool isTimeout) {
2719 *outCancelPreviousGesture = false;
2720 *outFinishPreviousGesture = false;
2721
2722 // Handle TAP timeout.
2723 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002724 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002725
Michael Wright227c5542020-07-02 18:30:52 +01002726 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002727 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2728 // The tap/drag timeout has not yet expired.
2729 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2730 mConfig.pointerGestureTapDragInterval);
2731 } else {
2732 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002733 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002734 *outFinishPreviousGesture = true;
2735
2736 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002737 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002738 mPointerGesture.currentGestureIdBits.clear();
2739
2740 mPointerVelocityControl.reset();
2741 return true;
2742 }
2743 }
2744
2745 // We did not handle this timeout.
2746 return false;
2747 }
2748
2749 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2750 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2751
2752 // Update the velocity tracker.
2753 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002754 std::vector<float> positionsX;
2755 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002756 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002757 uint32_t id = idBits.clearFirstMarkedBit();
2758 const RawPointerData::Pointer& pointer =
2759 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002760 positionsX.push_back(pointer.x * mPointerXMovementScale);
2761 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002762 }
2763 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002764 {{AMOTION_EVENT_AXIS_X, positionsX},
2765 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002766 }
2767
2768 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2769 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002770 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2771 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2772 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002773 mPointerGesture.resetTap();
2774 }
2775
2776 // Pick a new active touch id if needed.
2777 // Choose an arbitrary pointer that just went down, if there is one.
2778 // Otherwise choose an arbitrary remaining pointer.
2779 // This guarantees we always have an active touch id when there is at least one pointer.
2780 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002781 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002782 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002783 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002784 mPointerGesture.firstTouchTime = when;
2785 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002786 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2787 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2788 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2789 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002790 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002791 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002792
2793 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002794 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002796 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2797 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2798 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002799 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002800 *outFinishPreviousGesture = true;
2801 }
2802
2803 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002804 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002805 mPointerGesture.currentGestureIdBits.clear();
2806
2807 mPointerVelocityControl.reset();
2808 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2809 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2810 // The pointer follows the active touch point.
2811 // Emit DOWN, MOVE, UP events at the pointer location.
2812 //
2813 // Only the active touch matters; other fingers are ignored. This policy helps
2814 // to handle the case where the user places a second finger on the touch pad
2815 // to apply the necessary force to depress an integrated button below the surface.
2816 // We don't want the second finger to be delivered to applications.
2817 //
2818 // For this to work well, we need to make sure to track the pointer that is really
2819 // active. If the user first puts one finger down to click then adds another
2820 // finger to drag then the active pointer should switch to the finger that is
2821 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002822 ALOGD_IF(DEBUG_GESTURES,
2823 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2824 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002826 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002827 *outFinishPreviousGesture = true;
2828 mPointerGesture.activeGestureId = 0;
2829 }
2830
2831 // Switch pointers if needed.
2832 // Find the fastest pointer and follow it.
2833 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002834 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002835 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002836 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002837 ALOGD_IF(DEBUG_GESTURES,
2838 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2839 "bestSpeed=%0.3f",
2840 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002841 }
2842 }
2843
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002844 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002845 // When using spots, the click will occur at the position of the anchor
2846 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002847 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002848 } else {
2849 mPointerVelocityControl.reset();
2850 }
2851
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002852 float x, y;
2853 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854
Michael Wright227c5542020-07-02 18:30:52 +01002855 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856 mPointerGesture.currentGestureIdBits.clear();
2857 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2858 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2859 mPointerGesture.currentGestureProperties[0].clear();
2860 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2861 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2862 mPointerGesture.currentGestureCoords[0].clear();
2863 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2864 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2865 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2866 } else if (currentFingerCount == 0) {
2867 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002868 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869 *outFinishPreviousGesture = true;
2870 }
2871
2872 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2873 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2874 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002875 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2876 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002877 lastFingerCount == 1) {
2878 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002879 float x, y;
2880 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002881 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2882 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002883 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884
2885 mPointerGesture.tapUpTime = when;
2886 getContext()->requestTimeoutAtTime(when +
2887 mConfig.pointerGestureTapDragInterval);
2888
2889 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002890 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 mPointerGesture.currentGestureIdBits.clear();
2892 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2893 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2894 mPointerGesture.currentGestureProperties[0].clear();
2895 mPointerGesture.currentGestureProperties[0].id =
2896 mPointerGesture.activeGestureId;
2897 mPointerGesture.currentGestureProperties[0].toolType =
2898 AMOTION_EVENT_TOOL_TYPE_FINGER;
2899 mPointerGesture.currentGestureCoords[0].clear();
2900 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2901 mPointerGesture.tapX);
2902 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2903 mPointerGesture.tapY);
2904 mPointerGesture.currentGestureCoords[0]
2905 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2906
2907 tapped = true;
2908 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002909 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2910 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002911 }
2912 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002913 if (DEBUG_GESTURES) {
2914 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2915 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2916 (when - mPointerGesture.tapDownTime) * 0.000001f);
2917 } else {
2918 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2919 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002921 }
2922 }
2923
2924 mPointerVelocityControl.reset();
2925
2926 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002927 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002928 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002929 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002930 mPointerGesture.currentGestureIdBits.clear();
2931 }
2932 } else if (currentFingerCount == 1) {
2933 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2934 // The pointer follows the active touch point.
2935 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2936 // When in TAP_DRAG, emit MOVE events at the pointer location.
2937 ALOG_ASSERT(activeTouchId >= 0);
2938
Michael Wright227c5542020-07-02 18:30:52 +01002939 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2940 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002941 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002942 float x, y;
2943 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2945 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002946 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002947 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002948 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2949 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950 }
2951 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002952 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2953 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 }
Michael Wright227c5542020-07-02 18:30:52 +01002955 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2956 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002957 }
2958
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002959 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002960 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002961 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002962 } else {
2963 mPointerVelocityControl.reset();
2964 }
2965
2966 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002967 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002968 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002969 down = true;
2970 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002971 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002972 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 *outFinishPreviousGesture = true;
2974 }
2975 mPointerGesture.activeGestureId = 0;
2976 down = false;
2977 }
2978
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002979 float x, y;
2980 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981
2982 mPointerGesture.currentGestureIdBits.clear();
2983 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2984 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2985 mPointerGesture.currentGestureProperties[0].clear();
2986 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2987 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2988 mPointerGesture.currentGestureCoords[0].clear();
2989 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2990 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2991 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2992 down ? 1.0f : 0.0f);
2993
2994 if (lastFingerCount == 0 && currentFingerCount != 0) {
2995 mPointerGesture.resetTap();
2996 mPointerGesture.tapDownTime = when;
2997 mPointerGesture.tapX = x;
2998 mPointerGesture.tapY = y;
2999 }
3000 } else {
3001 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003002 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 }
3004
3005 mPointerController->setButtonState(mCurrentRawState.buttonState);
3006
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003007 if (DEBUG_GESTURES) {
3008 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3009 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3010 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3011 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3012 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3013 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3014 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3015 uint32_t id = idBits.clearFirstMarkedBit();
3016 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3017 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3018 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3019 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3020 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3021 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3022 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3023 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3024 }
3025 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3026 uint32_t id = idBits.clearFirstMarkedBit();
3027 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3028 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3029 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3030 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3031 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3032 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3033 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3034 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3035 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003036 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003037 return true;
3038}
3039
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003040bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3041 if (mPointerGesture.activeTouchId < 0) {
3042 mPointerGesture.resetQuietTime();
3043 return false;
3044 }
3045
3046 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3047 return true;
3048 }
3049
3050 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3051 bool isQuietTime = false;
3052 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3053 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3054 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3055 currentFingerCount < 2) {
3056 // Enter quiet time when exiting swipe or freeform state.
3057 // This is to prevent accidentally entering the hover state and flinging the
3058 // pointer when finishing a swipe and there is still one pointer left onscreen.
3059 isQuietTime = true;
3060 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3061 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3062 // Enter quiet time when releasing the button and there are still two or more
3063 // fingers down. This may indicate that one finger was used to press the button
3064 // but it has not gone up yet.
3065 isQuietTime = true;
3066 }
3067 if (isQuietTime) {
3068 mPointerGesture.quietTime = when;
3069 }
3070 return isQuietTime;
3071}
3072
3073std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3074 int32_t bestId = -1;
3075 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3076 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3077 uint32_t id = idBits.clearFirstMarkedBit();
3078 std::optional<float> vx =
3079 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3080 std::optional<float> vy =
3081 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3082 if (vx && vy) {
3083 float speed = hypotf(*vx, *vy);
3084 if (speed > bestSpeed) {
3085 bestId = id;
3086 bestSpeed = speed;
3087 }
3088 }
3089 }
3090 return std::make_pair(bestId, bestSpeed);
3091}
3092
3093void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3094 bool* finishPreviousGesture) {
3095 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3096 // to move before deciding what to do.
3097 //
3098 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3099 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3100 // just a press or long-press at the pointer location.
3101 //
3102 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3103 // pointer location.
3104 //
3105 // When the two fingers move enough or when additional fingers are added, we make a decision to
3106 // transition into SWIPE or FREEFORM mode accordingly.
3107 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3108 ALOG_ASSERT(activeTouchId >= 0);
3109
3110 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3111 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3112 bool settled =
3113 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3114 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3115 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3116 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3117 *finishPreviousGesture = true;
3118 } else if (!settled && currentFingerCount > lastFingerCount) {
3119 // Additional pointers have gone down but not yet settled.
3120 // Reset the gesture.
3121 ALOGD_IF(DEBUG_GESTURES,
3122 "Gestures: Resetting gesture since additional pointers went down for "
3123 "MULTITOUCH, settle time remaining %0.3fms",
3124 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3125 when) * 0.000001f);
3126 *cancelPreviousGesture = true;
3127 } else {
3128 // Continue previous gesture.
3129 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3130 }
3131
3132 if (*finishPreviousGesture || *cancelPreviousGesture) {
3133 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3134 mPointerGesture.activeGestureId = 0;
3135 mPointerGesture.referenceIdBits.clear();
3136 mPointerVelocityControl.reset();
3137
3138 // Use the centroid and pointer location as the reference points for the gesture.
3139 ALOGD_IF(DEBUG_GESTURES,
3140 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3141 "%0.3fms",
3142 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3143 when) * 0.000001f);
3144 mCurrentRawState.rawPointerData
3145 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3146 &mPointerGesture.referenceTouchY);
3147 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3148 &mPointerGesture.referenceGestureY);
3149 }
3150
3151 // Clear the reference deltas for fingers not yet included in the reference calculation.
3152 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3153 ~mPointerGesture.referenceIdBits.value);
3154 !idBits.isEmpty();) {
3155 uint32_t id = idBits.clearFirstMarkedBit();
3156 mPointerGesture.referenceDeltas[id].dx = 0;
3157 mPointerGesture.referenceDeltas[id].dy = 0;
3158 }
3159 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3160
3161 // Add delta for all fingers and calculate a common movement delta.
3162 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3163 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3164 mCurrentCookedState.fingerIdBits.value);
3165 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3166 bool first = (idBits == commonIdBits);
3167 uint32_t id = idBits.clearFirstMarkedBit();
3168 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3169 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3170 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3171 delta.dx += cpd.x - lpd.x;
3172 delta.dy += cpd.y - lpd.y;
3173
3174 if (first) {
3175 commonDeltaRawX = delta.dx;
3176 commonDeltaRawY = delta.dy;
3177 } else {
3178 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3179 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3180 }
3181 }
3182
3183 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3184 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3185 float dist[MAX_POINTER_ID + 1];
3186 int32_t distOverThreshold = 0;
3187 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3188 uint32_t id = idBits.clearFirstMarkedBit();
3189 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3190 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3191 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3192 distOverThreshold += 1;
3193 }
3194 }
3195
3196 // Only transition when at least two pointers have moved further than
3197 // the minimum distance threshold.
3198 if (distOverThreshold >= 2) {
3199 if (currentFingerCount > 2) {
3200 // There are more than two pointers, switch to FREEFORM.
3201 ALOGD_IF(DEBUG_GESTURES,
3202 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3203 currentFingerCount);
3204 *cancelPreviousGesture = true;
3205 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3206 } else {
3207 // There are exactly two pointers.
3208 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3209 uint32_t id1 = idBits.clearFirstMarkedBit();
3210 uint32_t id2 = idBits.firstMarkedBit();
3211 const RawPointerData::Pointer& p1 =
3212 mCurrentRawState.rawPointerData.pointerForId(id1);
3213 const RawPointerData::Pointer& p2 =
3214 mCurrentRawState.rawPointerData.pointerForId(id2);
3215 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3216 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3217 // There are two pointers but they are too far apart for a SWIPE,
3218 // switch to FREEFORM.
3219 ALOGD_IF(DEBUG_GESTURES,
3220 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3221 mutualDistance, mPointerGestureMaxSwipeWidth);
3222 *cancelPreviousGesture = true;
3223 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3224 } else {
3225 // There are two pointers. Wait for both pointers to start moving
3226 // before deciding whether this is a SWIPE or FREEFORM gesture.
3227 float dist1 = dist[id1];
3228 float dist2 = dist[id2];
3229 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3230 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3231 // Calculate the dot product of the displacement vectors.
3232 // When the vectors are oriented in approximately the same direction,
3233 // the angle betweeen them is near zero and the cosine of the angle
3234 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3235 // mag(v2).
3236 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3237 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3238 float dx1 = delta1.dx * mPointerXZoomScale;
3239 float dy1 = delta1.dy * mPointerYZoomScale;
3240 float dx2 = delta2.dx * mPointerXZoomScale;
3241 float dy2 = delta2.dy * mPointerYZoomScale;
3242 float dot = dx1 * dx2 + dy1 * dy2;
3243 float cosine = dot / (dist1 * dist2); // denominator always > 0
3244 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3245 // Pointers are moving in the same direction. Switch to SWIPE.
3246 ALOGD_IF(DEBUG_GESTURES,
3247 "Gestures: PRESS transitioned to SWIPE, "
3248 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3249 "cosine %0.3f >= %0.3f",
3250 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3251 mConfig.pointerGestureMultitouchMinDistance, cosine,
3252 mConfig.pointerGestureSwipeTransitionAngleCosine);
3253 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3254 } else {
3255 // Pointers are moving in different directions. Switch to FREEFORM.
3256 ALOGD_IF(DEBUG_GESTURES,
3257 "Gestures: PRESS transitioned to FREEFORM, "
3258 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3259 "cosine %0.3f < %0.3f",
3260 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3261 mConfig.pointerGestureMultitouchMinDistance, cosine,
3262 mConfig.pointerGestureSwipeTransitionAngleCosine);
3263 *cancelPreviousGesture = true;
3264 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3265 }
3266 }
3267 }
3268 }
3269 }
3270 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3271 // Switch from SWIPE to FREEFORM if additional pointers go down.
3272 // Cancel previous gesture.
3273 if (currentFingerCount > 2) {
3274 ALOGD_IF(DEBUG_GESTURES,
3275 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3276 currentFingerCount);
3277 *cancelPreviousGesture = true;
3278 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3279 }
3280 }
3281
3282 // Move the reference points based on the overall group motion of the fingers
3283 // except in PRESS mode while waiting for a transition to occur.
3284 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3285 (commonDeltaRawX || commonDeltaRawY)) {
3286 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3287 uint32_t id = idBits.clearFirstMarkedBit();
3288 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3289 delta.dx = 0;
3290 delta.dy = 0;
3291 }
3292
3293 mPointerGesture.referenceTouchX += commonDeltaRawX;
3294 mPointerGesture.referenceTouchY += commonDeltaRawY;
3295
3296 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3297 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3298
3299 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3300 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3301
3302 mPointerGesture.referenceGestureX += commonDeltaX;
3303 mPointerGesture.referenceGestureY += commonDeltaY;
3304 }
3305
3306 // Report gestures.
3307 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3308 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3309 // PRESS or SWIPE mode.
3310 ALOGD_IF(DEBUG_GESTURES,
3311 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3312 "currentTouchPointerCount=%d",
3313 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3314 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3315
3316 mPointerGesture.currentGestureIdBits.clear();
3317 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3318 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3319 mPointerGesture.currentGestureProperties[0].clear();
3320 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3321 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3322 mPointerGesture.currentGestureCoords[0].clear();
3323 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3324 mPointerGesture.referenceGestureX);
3325 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3326 mPointerGesture.referenceGestureY);
3327 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3328 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3329 float xOffset = static_cast<float>(commonDeltaRawX) /
3330 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3331 float yOffset = static_cast<float>(commonDeltaRawY) /
3332 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3333 mPointerGesture.currentGestureCoords[0]
3334 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3335 mPointerGesture.currentGestureCoords[0]
3336 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3337 }
3338 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3339 // FREEFORM mode.
3340 ALOGD_IF(DEBUG_GESTURES,
3341 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3342 "currentTouchPointerCount=%d",
3343 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3344 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3345
3346 mPointerGesture.currentGestureIdBits.clear();
3347
3348 BitSet32 mappedTouchIdBits;
3349 BitSet32 usedGestureIdBits;
3350 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3351 // Initially, assign the active gesture id to the active touch point
3352 // if there is one. No other touch id bits are mapped yet.
3353 if (!*cancelPreviousGesture) {
3354 mappedTouchIdBits.markBit(activeTouchId);
3355 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3356 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3357 mPointerGesture.activeGestureId;
3358 } else {
3359 mPointerGesture.activeGestureId = -1;
3360 }
3361 } else {
3362 // Otherwise, assume we mapped all touches from the previous frame.
3363 // Reuse all mappings that are still applicable.
3364 mappedTouchIdBits.value =
3365 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3366 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3367
3368 // Check whether we need to choose a new active gesture id because the
3369 // current went went up.
3370 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3371 ~mCurrentCookedState.fingerIdBits.value);
3372 !upTouchIdBits.isEmpty();) {
3373 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3374 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3375 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3376 mPointerGesture.activeGestureId = -1;
3377 break;
3378 }
3379 }
3380 }
3381
3382 ALOGD_IF(DEBUG_GESTURES,
3383 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3384 "activeGestureId=%d",
3385 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3386
3387 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3388 for (uint32_t i = 0; i < currentFingerCount; i++) {
3389 uint32_t touchId = idBits.clearFirstMarkedBit();
3390 uint32_t gestureId;
3391 if (!mappedTouchIdBits.hasBit(touchId)) {
3392 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3393 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3394 ALOGD_IF(DEBUG_GESTURES,
3395 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3396 gestureId);
3397 } else {
3398 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3399 ALOGD_IF(DEBUG_GESTURES,
3400 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3401 touchId, gestureId);
3402 }
3403 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3404 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3405
3406 const RawPointerData::Pointer& pointer =
3407 mCurrentRawState.rawPointerData.pointerForId(touchId);
3408 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3409 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3410 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3411
3412 mPointerGesture.currentGestureProperties[i].clear();
3413 mPointerGesture.currentGestureProperties[i].id = gestureId;
3414 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3415 mPointerGesture.currentGestureCoords[i].clear();
3416 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3417 mPointerGesture.referenceGestureX +
3418 deltaX);
3419 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3420 mPointerGesture.referenceGestureY +
3421 deltaY);
3422 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3423 }
3424
3425 if (mPointerGesture.activeGestureId < 0) {
3426 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3427 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3428 mPointerGesture.activeGestureId);
3429 }
3430 }
3431}
3432
Harry Cutts714d1ad2022-08-24 16:36:43 +00003433void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3434 const RawPointerData::Pointer& currentPointer =
3435 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3436 const RawPointerData::Pointer& lastPointer =
3437 mLastRawState.rawPointerData.pointerForId(pointerId);
3438 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3439 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3440
3441 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3442 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3443
3444 mPointerController->move(deltaX, deltaY);
3445}
3446
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003447std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3448 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003449 mPointerSimple.currentCoords.clear();
3450 mPointerSimple.currentProperties.clear();
3451
3452 bool down, hovering;
3453 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3454 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3455 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003456 mPointerController
3457 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3458 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003459
3460 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3461 down = !hovering;
3462
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003463 float x, y;
3464 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003465 mPointerSimple.currentCoords.copyFrom(
3466 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3467 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3468 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3469 mPointerSimple.currentProperties.id = 0;
3470 mPointerSimple.currentProperties.toolType =
3471 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3472 } else {
3473 down = false;
3474 hovering = false;
3475 }
3476
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003477 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003478}
3479
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003480std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3481 uint32_t policyFlags) {
3482 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003483}
3484
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003485std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3486 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003487 mPointerSimple.currentCoords.clear();
3488 mPointerSimple.currentProperties.clear();
3489
3490 bool down, hovering;
3491 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3492 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003493 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003494 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003495 } else {
3496 mPointerVelocityControl.reset();
3497 }
3498
3499 down = isPointerDown(mCurrentRawState.buttonState);
3500 hovering = !down;
3501
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003502 float x, y;
3503 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003504 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003505 mPointerSimple.currentCoords.copyFrom(
3506 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3507 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3508 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3509 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3510 hovering ? 0.0f : 1.0f);
3511 mPointerSimple.currentProperties.id = 0;
3512 mPointerSimple.currentProperties.toolType =
3513 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3514 } else {
3515 mPointerVelocityControl.reset();
3516
3517 down = false;
3518 hovering = false;
3519 }
3520
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003521 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003522}
3523
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003524std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3525 uint32_t policyFlags) {
3526 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527
3528 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003529
3530 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003531}
3532
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003533std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3534 uint32_t policyFlags, bool down,
3535 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003536 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3537 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003538 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003539 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003540
3541 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003542 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003543 mPointerController->clearSpots();
3544 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003545 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003547 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003548 }
Garfield Tan9514d782020-11-10 16:37:23 -08003549 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003550
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003551 float xCursorPosition, yCursorPosition;
3552 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003553
3554 if (mPointerSimple.down && !down) {
3555 mPointerSimple.down = false;
3556
3557 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003558 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3559 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3560 0, metaState, mLastRawState.buttonState,
3561 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3562 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3563 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3564 yCursorPosition, mPointerSimple.downTime,
3565 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003566 }
3567
3568 if (mPointerSimple.hovering && !hovering) {
3569 mPointerSimple.hovering = false;
3570
3571 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003572 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3573 mSource, displayId, policyFlags,
3574 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3575 mLastRawState.buttonState, MotionClassification::NONE,
3576 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3577 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3578 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3579 yCursorPosition, mPointerSimple.downTime,
3580 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003581 }
3582
3583 if (down) {
3584 if (!mPointerSimple.down) {
3585 mPointerSimple.down = true;
3586 mPointerSimple.downTime = when;
3587
3588 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003589 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3590 mSource, displayId, policyFlags,
3591 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3592 mCurrentRawState.buttonState, MotionClassification::NONE,
3593 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3594 &mPointerSimple.currentProperties,
3595 &mPointerSimple.currentCoords, mOrientedXPrecision,
3596 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3597 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598 }
3599
3600 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003601 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3602 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3603 0, 0, metaState, mCurrentRawState.buttonState,
3604 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3605 &mPointerSimple.currentProperties,
3606 &mPointerSimple.currentCoords, mOrientedXPrecision,
3607 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3608 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003609 }
3610
3611 if (hovering) {
3612 if (!mPointerSimple.hovering) {
3613 mPointerSimple.hovering = true;
3614
3615 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003616 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3617 mSource, displayId, policyFlags,
3618 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3619 mCurrentRawState.buttonState, MotionClassification::NONE,
3620 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3621 &mPointerSimple.currentProperties,
3622 &mPointerSimple.currentCoords, mOrientedXPrecision,
3623 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3624 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003625 }
3626
3627 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003628 out.push_back(
3629 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3630 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3631 metaState, mCurrentRawState.buttonState,
3632 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3633 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3634 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3635 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003636 }
3637
3638 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3639 float vscroll = mCurrentRawState.rawVScroll;
3640 float hscroll = mCurrentRawState.rawHScroll;
3641 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3642 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3643
3644 // Send scroll.
3645 PointerCoords pointerCoords;
3646 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3647 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3648 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3649
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003650 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3651 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3652 0, 0, metaState, mCurrentRawState.buttonState,
3653 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3654 &mPointerSimple.currentProperties, &pointerCoords,
3655 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3656 yCursorPosition, mPointerSimple.downTime,
3657 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003658 }
3659
3660 // Save state.
3661 if (down || hovering) {
3662 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3663 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003664 mPointerSimple.displayId = displayId;
3665 mPointerSimple.source = mSource;
3666 mPointerSimple.lastCursorX = xCursorPosition;
3667 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003668 } else {
3669 mPointerSimple.reset();
3670 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003671 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003672}
3673
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003674std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3675 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003676 std::list<NotifyArgs> out;
3677 if (mPointerSimple.down || mPointerSimple.hovering) {
3678 int32_t metaState = getContext()->getGlobalMetaState();
3679 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3680 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3681 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3682 metaState, mLastRawState.buttonState,
3683 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3684 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3685 mOrientedXPrecision, mOrientedYPrecision,
3686 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3687 mPointerSimple.downTime,
3688 /* videoFrames */ {}));
3689 if (mPointerController != nullptr) {
3690 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3691 }
3692 }
3693 mPointerSimple.reset();
3694 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003695}
3696
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003697NotifyMotionArgs TouchInputMapper::dispatchMotion(
3698 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3699 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003700 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3701 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003702 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003703 PointerCoords pointerCoords[MAX_POINTERS];
3704 PointerProperties pointerProperties[MAX_POINTERS];
3705 uint32_t pointerCount = 0;
3706 while (!idBits.isEmpty()) {
3707 uint32_t id = idBits.clearFirstMarkedBit();
3708 uint32_t index = idToIndex[id];
3709 pointerProperties[pointerCount].copyFrom(properties[index]);
3710 pointerCoords[pointerCount].copyFrom(coords[index]);
3711
3712 if (changedId >= 0 && id == uint32_t(changedId)) {
3713 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3714 }
3715
3716 pointerCount += 1;
3717 }
3718
3719 ALOG_ASSERT(pointerCount != 0);
3720
3721 if (changedId >= 0 && pointerCount == 1) {
3722 // Replace initial down and final up action.
3723 // We can compare the action without masking off the changed pointer index
3724 // because we know the index is 0.
3725 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3726 action = AMOTION_EVENT_ACTION_DOWN;
3727 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003728 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3729 action = AMOTION_EVENT_ACTION_CANCEL;
3730 } else {
3731 action = AMOTION_EVENT_ACTION_UP;
3732 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003733 } else {
3734 // Can't happen.
3735 ALOG_ASSERT(false);
3736 }
3737 }
3738 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3739 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003740 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003741 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003742 }
3743 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3744 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003745 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003746 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003747 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003748 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3749 policyFlags, action, actionButton, flags, metaState, buttonState,
3750 classification, edgeFlags, pointerCount, pointerProperties,
3751 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3752 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003753}
3754
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003755std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3756 std::list<NotifyArgs> out;
3757 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3758 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3759 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003760}
3761
Prabir Pradhan1728b212021-10-19 16:00:03 -07003762bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003763 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003764 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003765 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003766}
3767
3768const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3769 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003770 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3771 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3772 "left=%d, top=%d, right=%d, bottom=%d",
3773 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3774 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003775
3776 if (virtualKey.isHit(x, y)) {
3777 return &virtualKey;
3778 }
3779 }
3780
3781 return nullptr;
3782}
3783
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003784void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3785 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3786 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003787
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003788 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003789
3790 if (currentPointerCount == 0) {
3791 // No pointers to assign.
3792 return;
3793 }
3794
3795 if (lastPointerCount == 0) {
3796 // All pointers are new.
3797 for (uint32_t i = 0; i < currentPointerCount; i++) {
3798 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003799 current.rawPointerData.pointers[i].id = id;
3800 current.rawPointerData.idToIndex[id] = i;
3801 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003802 }
3803 return;
3804 }
3805
3806 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003807 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003808 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003809 uint32_t id = last.rawPointerData.pointers[0].id;
3810 current.rawPointerData.pointers[0].id = id;
3811 current.rawPointerData.idToIndex[id] = 0;
3812 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003813 return;
3814 }
3815
3816 // General case.
3817 // We build a heap of squared euclidean distances between current and last pointers
3818 // associated with the current and last pointer indices. Then, we find the best
3819 // match (by distance) for each current pointer.
3820 // The pointers must have the same tool type but it is possible for them to
3821 // transition from hovering to touching or vice-versa while retaining the same id.
3822 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3823
3824 uint32_t heapSize = 0;
3825 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3826 currentPointerIndex++) {
3827 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3828 lastPointerIndex++) {
3829 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003830 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003831 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003832 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003833 if (currentPointer.toolType == lastPointer.toolType) {
3834 int64_t deltaX = currentPointer.x - lastPointer.x;
3835 int64_t deltaY = currentPointer.y - lastPointer.y;
3836
3837 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3838
3839 // Insert new element into the heap (sift up).
3840 heap[heapSize].currentPointerIndex = currentPointerIndex;
3841 heap[heapSize].lastPointerIndex = lastPointerIndex;
3842 heap[heapSize].distance = distance;
3843 heapSize += 1;
3844 }
3845 }
3846 }
3847
3848 // Heapify
3849 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3850 startIndex -= 1;
3851 for (uint32_t parentIndex = startIndex;;) {
3852 uint32_t childIndex = parentIndex * 2 + 1;
3853 if (childIndex >= heapSize) {
3854 break;
3855 }
3856
3857 if (childIndex + 1 < heapSize &&
3858 heap[childIndex + 1].distance < heap[childIndex].distance) {
3859 childIndex += 1;
3860 }
3861
3862 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3863 break;
3864 }
3865
3866 swap(heap[parentIndex], heap[childIndex]);
3867 parentIndex = childIndex;
3868 }
3869 }
3870
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003871 if (DEBUG_POINTER_ASSIGNMENT) {
3872 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3873 for (size_t i = 0; i < heapSize; i++) {
3874 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3875 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3876 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003877 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003878
3879 // Pull matches out by increasing order of distance.
3880 // To avoid reassigning pointers that have already been matched, the loop keeps track
3881 // of which last and current pointers have been matched using the matchedXXXBits variables.
3882 // It also tracks the used pointer id bits.
3883 BitSet32 matchedLastBits(0);
3884 BitSet32 matchedCurrentBits(0);
3885 BitSet32 usedIdBits(0);
3886 bool first = true;
3887 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3888 while (heapSize > 0) {
3889 if (first) {
3890 // The first time through the loop, we just consume the root element of
3891 // the heap (the one with smallest distance).
3892 first = false;
3893 } else {
3894 // Previous iterations consumed the root element of the heap.
3895 // Pop root element off of the heap (sift down).
3896 heap[0] = heap[heapSize];
3897 for (uint32_t parentIndex = 0;;) {
3898 uint32_t childIndex = parentIndex * 2 + 1;
3899 if (childIndex >= heapSize) {
3900 break;
3901 }
3902
3903 if (childIndex + 1 < heapSize &&
3904 heap[childIndex + 1].distance < heap[childIndex].distance) {
3905 childIndex += 1;
3906 }
3907
3908 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3909 break;
3910 }
3911
3912 swap(heap[parentIndex], heap[childIndex]);
3913 parentIndex = childIndex;
3914 }
3915
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003916 if (DEBUG_POINTER_ASSIGNMENT) {
3917 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3918 for (size_t j = 0; j < heapSize; j++) {
3919 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3920 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3921 heap[j].distance);
3922 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003923 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003924 }
3925
3926 heapSize -= 1;
3927
3928 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3929 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3930
3931 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3932 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3933
3934 matchedCurrentBits.markBit(currentPointerIndex);
3935 matchedLastBits.markBit(lastPointerIndex);
3936
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003937 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3938 current.rawPointerData.pointers[currentPointerIndex].id = id;
3939 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3940 current.rawPointerData.markIdBit(id,
3941 current.rawPointerData.isHovering(
3942 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003943 usedIdBits.markBit(id);
3944
Harry Cutts45483602022-08-24 14:36:48 +00003945 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3946 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3947 ", distance=%" PRIu64,
3948 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003949 break;
3950 }
3951 }
3952
3953 // Assign fresh ids to pointers that were not matched in the process.
3954 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3955 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3956 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3957
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003958 current.rawPointerData.pointers[currentPointerIndex].id = id;
3959 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3960 current.rawPointerData.markIdBit(id,
3961 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003962
Harry Cutts45483602022-08-24 14:36:48 +00003963 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3964 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
3965 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003966 }
3967}
3968
3969int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3970 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3971 return AKEY_STATE_VIRTUAL;
3972 }
3973
3974 for (const VirtualKey& virtualKey : mVirtualKeys) {
3975 if (virtualKey.keyCode == keyCode) {
3976 return AKEY_STATE_UP;
3977 }
3978 }
3979
3980 return AKEY_STATE_UNKNOWN;
3981}
3982
3983int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3984 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3985 return AKEY_STATE_VIRTUAL;
3986 }
3987
3988 for (const VirtualKey& virtualKey : mVirtualKeys) {
3989 if (virtualKey.scanCode == scanCode) {
3990 return AKEY_STATE_UP;
3991 }
3992 }
3993
3994 return AKEY_STATE_UNKNOWN;
3995}
3996
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003997bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
3998 const std::vector<int32_t>& keyCodes,
3999 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004000 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004001 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004002 if (virtualKey.keyCode == keyCodes[i]) {
4003 outFlags[i] = 1;
4004 }
4005 }
4006 }
4007
4008 return true;
4009}
4010
4011std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4012 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004013 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004014 return std::make_optional(mPointerController->getDisplayId());
4015 } else {
4016 return std::make_optional(mViewport.displayId);
4017 }
4018 }
4019 return std::nullopt;
4020}
4021
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004022} // namespace android